Reputation: 1124
I'm trying to use the following code to compare a file's version to a specified version, and tell me which one is higher.
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
FYI using ProductVersion instead of FileVersion because FileVersion seems to contain extra data sometimes.
It returns "file is a lower version" even though that's the same version that is displayed in Properties.
Do I need to do something else to get it to compare the ProductVersion property to a string?
Upvotes: 1
Views: 10835
Reputation: 12289
PowerShell functions don't work like typical other language functions. You don't "return" a value. Instead, you output it to the Pipeline for display or further processing using Write-Output. If you do it correctly, the output will be an actual System.Diagnostics.FileVersionInfo object from which you can compare versions. See revised code below.
function Get-FileVersionInfo
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$FileName)
if(!(test-path $filename)) {
Write-Error "File not found"
}
Write-Output ([System.Diagnostics.FileVersionInfo]::GetVersionInfo($FileName))
}
$version = Get-FileVersionInfo -FileName "C:\Program Files\Internet Explorer\iexplore.exe"
$version | Get-Member
$version.FileMajorPart
$version.FileMinorPart
$version.FileVersion
Upvotes: 0
Reputation: 4034
You don't compare that Property to a string. Create a [System.Version]-object from the string.
fixed code:
$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"
}
Upvotes: 6