我有一个案例,我必须根据比较版本在脚本中做出决定 考虑这个例子:
PS C:\>
[version]$SomeVersion='1.1.1'
[version]$OtherVersion='1.1.1.0'
PS C:\> $SomeVersion
Major Minor Build Revision
----- ----- ----- --------
1 1 1 -1
PS C:\> $OtherVersion
Major Minor Build Revision
----- ----- ----- --------
1 1 1 0
PS C:\>$SomeVersion -ge $OtherVersion
False
我想在比较System.Version类型的对象时省略修订
我找不到任何理智的方式。
有没有?
注意 - 我尝试过:
PS C:\> ($scriptversion |select major,minor,build) -gt ($currentVersion|select major,minor,build)
Cannot compare "@{Major=1; Minor=1; Build=1}" to "@{Major=1; Minor=1;
Build=1}" because the objects are not the same type or the object "@{Major=1;
Minor=1; Build=1}" does not implement "IComparable".
At line:1 char:1
+ ($scriptversion |select major,minor,build) -gt ($currentVersion |sele ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : PSObjectCompareTo
当我尝试用0覆盖修订号时,它表示它是只读属性... 我有一个解决方法但我希望用system.version
做得更好答案 0 :(得分:4)
使用three argument System.Version
constructor创建具有相关属性的新实例:
[Version]::new($scriptversion.Major,$scriptversion.Minor,$scriptversion.Build) -gt [Version]::new($currentVersion.Major,$currentVersion.Minor,$currentVersion.Build)
或者您可以使用New-Object
:
$NormalizedScriptVersion = New-Object -TypeName System.Version -ArgumentList $scriptversion.Major,$scriptversion.Minor,$scriptversion.Build
$NormalizedCurrentVersion = New-Object -TypeName System.Version -ArgumentList $currentVersion.Major,$currentVersion.Minor,$currentVersion.Build
$NormalizedScriptVersion -gt $NormalizedCurrentVersion
使用您认为更易于维护的那些。
答案 1 :(得分:2)
最简单的方法是将Version对象转换为可比较的字符串:
filter Convert-VersionToComparableText { '{0:0000000000}{1:0000000000}{2:0000000000}' -f $_.Major, $_.Minor, $_.Build }
$SomeVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion
$SomeVersion = [Version]'1.2.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion
$SomeVersion = [Version]'1.1.1' | Convert-VersionToComparableText
$OtherVersion = [Version]'1.2.1' | Convert-VersionToComparableText
$SomeVersion -ge $OtherVersion
输出:
True
True
False