Home » How to Compare Version Numbers in PowerShell

How to Compare Version Numbers in PowerShell

In PowerShell, you can compare version numbers using the Compare-Object cmdlet or comparison operators.

In this article, we will learn how to compare two version numbers in PowerShell using the different methods available.

How to Compare Version Numbers using Compare-Object in PowerShell

To compare version numbers in PowerShell, use the Compare-Object cmdlet. This command uses the -ReferenceObject and -DifferenceObject parameter to find any difference in the version numbers.

The following example demonstrates comparing version numbers using the Compare-Object cmdlet in PowerShell.

# Declare version numbers
$version1 = "1.2.3"
$version2 = "1.2.4"

# Compare version numbers
$result = Compare-Object -ReferenceObject ([version]$version1) -DifferenceObject ([version]$version2)

if ($result -eq $null) {
    Write-Host "Version 1 is equal to Version 2"
} elseif ($result.SideIndicator -eq "=>") {
    Write-Host "Version 1 is less than Version 2"
} elseif ($result.SideIndicator -eq "<=") {
    Write-Host "Version 1 is greater than Version 2"
}

Result:

Version 1 is less than Version 2

In the above PowerShell script, the $version1 and $version2 variables stores the version numbers. The Compare-Object cmdlet in PowerShell used to compare these two version numbers and store any differences in the $result variable.

The if-else statement used to check if the $result variable match with the specified criteria to print the output value.

Compare Version Numbers Using the Version Class

You can use the version class to compare two version numbers in PowerShell.

In the following example, it uses the version class and comparison operators such as -lt, -gt, and -eq to compare objects.

$version1 = [Version] "1.2.3"
$version2 = [Version] "1.2.4"
if ($version1 -lt $version2) {
    Write-Host "$version1 is less than $version2"
} elseif ($version1 -gt $version2) {
    Write-Host "$version1 is greater than $version2"
} else {
    Write-Host "$version1 is equal to $version2"
}

Result:

1.2.3 is less than 1.2.4

Conclusion

I hope the above article on how to compare two version numbers in PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.