Comparing Versions
When thought of as version numbers 1.0.100 is a newer version than 1.0.99 but below the are compared as strings:[string] $versionPrevious = '1.0.99'
[string] $versionCurrent = '1.0.100'
if ($versionCurrent -gt $versionPrevious) {
Write-Host
"Correct: `$versionCurrent ($versionCurrent) -gt" +
"`$versionPrevious ($versionPrevious)"
}else {
Write-Host
"Incorrect: `$versionPrevious ($versionPrevious) -gt" +
" `$versionCurrent ($versionCurrent)"
}The output from the previous code is as expected the result of a string compare using the -gt operator which is not the same a comparison between version numbers:
Incorrect: $versionPrevious (1.0.99) -gt $versionCurrent (1.0.100)
.NET provides a class System.Version for representing version numbers. In PowerShell this calls is presented by the type [version]. The System.NET version type is described by Microsoft in https://docs.microsoft.com/ as follows:
Changing the variable type from [string] to [version] results in the version numbers be compared correctly:
[version] $versionPrevious = '1.0.99'
[version] $versionCurrent = '1.0.100'
if ($versionCurrent -gt $versionPrevious) {
Write-Host
"Correct: `$versionCurrent ($versionCurrent) -gt" +
"`$versionPrevious ($versionPrevious)"
}
else {
Write-Host
"Incorrect: `$versionPrevious ($versionPrevious) -gt" +
" `$versionCurrent ($versionCurrent)"
}
The output from the previous code is as expected the result of a version using the -gt operator:
Correct: $versionCurrent (1.0.100) -gt $versionPrevious (1.0.99)
A final note, the Escape Character
The previous code snippet contained two instance of the back quote character being used to suppress the $ character's use in a double quoted string `$versionCurrent and `$versionCurrent. A PowerShell variable inside of a double quoted string is results in the value of the variable being replaced inside the string. The back quote before $ suppresses this substitution
No comments :
Post a Comment