Powershell脚本比较文件数组结果版本要删除的问题



破坏我的逻辑电路,因为我无法用一些来理解Powershell。NET为该比较文件数组结果抛出。从数组结果中,脚本将每个结果文件的版本与设置的版本进行比较,如果低于/不等于设置的版本,则删除该文件。我试图在Powershell中使用示例比较文件版本,但我找不到输出问题,即为什么该行为在Windows Server 2019与Windows 10 Enterprise上有效。从MS Teams Machine Wide垃圾中删除旧的配置文件Teams.exe数据。非常感谢您的协助!

我的脚本通过MS Endpoint/SCM 部署

$TeamsPath = 'C:Users*AppDataLocalMicrosoftTeamscurrentTeams.exe'
$FileVersion = @(Get-ChildItem -Path $TeamsPath -Recurse -Force)
foreach ($TeamsPath in $FileVersion){
$ProductVersion = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($TeamsPath).ProductVersion
$TargetVersion = [System.Version]::Parse("1.3.0.13000")
if ($ProductVersion -le $TargetVersion){
Remove-Item -Path $TeamsPath.Directory -Force -Recurse
}
}

对原始答案进行了修订,以拥有一个正确而干净的例程来从旧的用户配置文件中删除/卸载团队

$TeamsPath = 'C:Users*AppDataLocalMicrosoftTeams'
$TargetVersion = [version] '1.3.0.13000'
Get-ChildItem -Path $TeamsPath -Filter "Teams.exe" -Force -Recurse | 
ForEach-Object {
if ([version] $_.VersionInfo.ProductVersion -le $TargetVersion) {

$UpdateRun = Split-Path $_.DirectoryName 

Start-Process -FilePath "$UpdateRunUpdate.exe" -ArgumentList "--uninstall /s" -PassThru -Wait -ErrorAction STOP

#Remove-Item -LiteralPath $_.DirectoryName  -Force -Recurse -WhatIf
}
}

代码的问题:

  • (这可能是发布工件(您希望在所有用户的AppData文件夹上循环,因此通配符路径必须以'C:Users*...而不是C:Users*...开头,也就是说,*必须是其自己的路径组件。

  • 不需要调用[System.Diagnostics.FileVersionInfo]::GetVersionInfo($TeamsPath),因为PowerShell用来装饰System.IO.FileInfo实例的.VersionInfoETS属性在后台执行的正是该调用。

  • .ProductVersion属性包含版本号的字符串表示;如果将其用作-le比较的LHS,则执行字符串比较(然后[version](System.Version(RHS也被强制为字符串(。

以下是已更正问题的代码的精简版本:

$teamsPath = 'C:Users*AppDataLocalMicrosoftTeamscurrentTeams.exe'
$targetVersion = [version] '1.3.0.13000'
Get-ChildItem -Path $teamsPath -Force | 
ForEach-Object {
if ([version] $_.VersionInfo.ProductVersion -le $targetVersion) {
Remove-Item -LiteralPath $_.DirectoryName  -Force -Recurse -WhatIf
}
}

注意:上面命令中的-WhatIf公共参数预览操作。一旦您确定操作将执行您想要的操作,请删除-WhatIf

最新更新