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: How To Invoke Rest Method with RingCentral Rest API

[string]$restApiTokenUrl="https://platform.ringcentral.com/restapi/oauth/token" [string]$restApiUrl="https://platform.ringcentral.com/restapi/v1.0/account/~/extension?page=1" [string]$username='15555555555' [string]$password='PASSWORDHERE' [string]$extension='100' [string]$appKey='APPKEYHERE' # Part 1: Obtain Rest-API Token / Authorization function…

PowerShell Script to Clean Up Files Older than X Days

$purgePeriod = 30;$folders = '\\FILSERVER01\ORDERS\BACKUP','C:\SFTP_BACKUP';Get-ChildItem -path $folders | where {$_.Lastwritetime -lt (date).adddays(-$purgePeriod)} | remove-item;

Linux: GREP Training

Lorum Ipsum - let's learn about grep, ya'll Examples: # Get information only on the…