在 Powershell 中比较文件版本

Pic*_*kle 1 powershell

我正在尝试使用以下代码将文件的版本与指定版本进行比较,并告诉我哪个版本更高。

function Get-FileVersionInfo            
{            
  param(            
    [Parameter(Mandatory=$true)]            
     [string]$FileName)            

  if(!(test-path $filename)) {            
  write-host "File not found"            
  return $null            
  }            

  return [System.Diagnostics.FileVersionInfo]::GetVersionInfo($FileName)            

}

$file = Get-FileVersionInfo("C:\program files\internet explorer\iexplore.exe")


if($file.ProductVersion -gt "11.00.9600.17840") {
    echo "file is higher version"
}
elseif($file.ProductVersion -eq "11.00.9600.17840") {
    echo "file is equal version"
}
else {
    echo "file is lower version"
}

echo "Product version is:" $file.ProductVersion
Run Code Online (Sandbox Code Playgroud)

仅供参考,使用 ProductVersion 而不是 FileVersion,因为 FileVersion 有时似乎包含额外的数据。

它返回“文件是较低版本”,即使它与“属性”中显示的版本相同。

我是否需要执行其他操作才能将 ProductVersion 属性与字符串进行比较?

D.J*_*.J. 6

您不将该属性与字符串进行比较。从字符串创建一个 [System.Version] 对象。

固定代码:

    $version = [System.Version]::Parse("11.00.9600.17840")
if($file.ProductVersion -gt $version) {
    echo "file is higher version"
}
elseif($file.ProductVersion -eq $version) {
    echo "file is equal version"
}
else {
    echo "file is lower version"
}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用“ProductVersionRaw”来执行此操作。 (2认同)