Posted On May 14, 2020

PowerShell: Comparing Software Versions

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Comparing Software Versions

This is a reusable function to enable quick comparisons between two strings representing version control numbers. I’ve adapted this from JavaScript with the pleasure of being able call the PowerShell [version] object constructor. Windows do make certain activities easier.

# Shorter version
function isHigherVersion ($a,$b){
    # This assumes the query as version $a is greater than $b by reconstructing PowerShell version object 
    $regexVersion='^(\d+)\.{1}(\d+)\.{0,1}(\d+){0,1}\.{0,1}(\d+){0,1}'
    [void]($a -match $regexVersion)
1..4|%{new-variable "a$_" -value $matches[$_] -force}   
    [void]($b -match $regexVersion)
1..4|%{new-variable "b$_" -value $matches[$_] -force}
    return [Version]::new($a1,$a2,$a3,$a4) -gt [Version]::new($b1,$b2,$b3,$b4)
}
# Overly verbose version
function compareVersions ($a,$b){
    # This assumes the query as version $a is greater than $b by reconstructing PowerShell version object 
    $majorRegex = '^(\d+)\.'
    $minorRegex = '^\d+\.(\d+)'
    $buildRegex = '^\d+\.\d+\.(\d+)'
    $revisionRegex = '^\d+\.\d+\.\d+\.(\d+)'
    $aMajor= .{[void]($a -match $majorRegex);return $matches[1]}
    $aMinor= .{[void]($a -match $minorRegex);return $matches[1]}
    $aBuild= .{[void]($a -match $buildRegex);return $matches[1]}
    $aRevision=.{[void]($a -match $revisionRegex);return $matches[1]}
    $bMajor= .{[void]($b -match $majorRegex);return $matches[1]}
    $bMinor= .{[void]($b -match $minorRegex);return $matches[1]}
    $bBuild= .{[void]($b -match $buildRegex);return $matches[1]}
    $bRevision=.{[void]($b -match $revisionRegex);return $matches[1]}
    return [Version]::new($aMajor,$aMinor,$aBuild,$aRevision) -gt [Version]::new($bMajor,$bMinor,$bBuild,$bRevision)
}
PS C:\Windows\system32> compareVersions 1.1.1.1 1.1.0.2
True

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Get Active Directory Domain Controller Replication Status

$domaincontroller=(Get-ADForest |Select-Object -ExpandProperty RootDomain |Get-ADDomain |Select-Object -Property PDCEmulator).PDCEmulator; ## Define Objects ## $report = New-Object…

PowerShell: Install Windows Exporter

Simple Version $windowsExporterUrl='https://github.com/prometheus-community/windows_exporter/releases/download/v0.20.0/windows_exporter-0.20.0-amd64.msi' $stageFolder='C:\Temp\' # Download the file Import-Module BitsTransfer $fileName=[regex]::match($windowsExporterUrl,'[^/\\&\?]+\.\w{3,4}(?=([\?&].*$|$))') $msiFile=join-path $stageFolder $fileName if(!(test-path…

PowerShell: Renaming a System File

System files are typically owned by the TrustedInstaller account and protected from deletion or changes.…
Other project: DragonCoin.com