Compare version numbers

Arosh Wijepala 161 Reputation points
2021-08-11T13:38:45.183+00:00

Hi,

I have this below code to compare 2 version numbers. However It does not work as expected as v9.4.11 is taken as grater version number than v11.2.5. How can I achive comparing 2 version numbers? Thanks.

$INSV=9.4.11
$NWTV=11.2.5
If ([version]$INSV -lt [version]$NWTV){
Write-Host "Perfrom rest of the work!"
}
Else {
Write-Host "Exit!"}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Rich B 6 Reputation points
    2024-05-20T10:21:18.9233333+00:00

    Your inputs should be strings, then you can cast them correctly to the System.Version type:

    [System.Version]$INSV="9.4.11"
    [System.Version]$NWTV="11.2.5"
    If ($INSV -lt $NWTV){
    Write-Host "Perfrom rest of the work!"
    }
    Else {
    Write-Host "Exit!"}
    
    1 person found this answer helpful.

  2. Rich Matheisen 45,906 Reputation points
    2021-08-11T14:53:05.287+00:00

    Use strings:

    $INSV="9.4.11"
    $NWTV="11.2.5"
    If ([version]$INSV -lt [version]$NWTV){
        Write-Host "Perfrom rest of the work!"
    }
    Else {
        Write-Host "Exit!"
    }
    
    0 comments No comments