Compare the software version number in PowerShell

Viewed 1264

I use PowerShell to install software, I need to compare the version number. Some software version numbers are divided into multiple sections, how to compare? Here's an example:

$Old_ver=18.05
$New_ver=19.00

if ($New_ver -gt $Old_ver) {
    Write-Output "You need to install a new version"
} elseif ($New_ver -eq $Old_ver) {
    Write-Output "You have already installed"
} else {
    Write-Output "You have installed a new version"
}
2 Answers

Define your version numbers as strings and cast them to [version] objects.

[version]$Old_ver = '18.05'
[version]$New_ver = '19.00'

Besides casting to [Version], you could also instantiate the Version objects directly:

$Old_ver = [Version]::new(18, 5)
$New_ver = [Version]::new(19, 0)

or

$Old_ver = [Version]::new('18.05')
$New_ver = [Version]::new('19.00')
Related