Functions/Validations/Test-PsVersion.ps1
<#
.SYNOPSIS Tests if the PowerShell version meets the minimal PowerShell version requirements .DESCRIPTION Returns $true if the PowerShell session meets the minimal required version and $false when not. .EXAMPLE Test-PsVersion .EXAMPLE # Returns either $true or $false but supresses the warning when the PowerShell version is too low. Test-PsVersion -WarningAction SilentlyContinue .EXAMPLE # Log a warning when the PowerShell version is too low but ignores the $false output. Test-PsVersion -MinimalVersion '5.1.19041.1237' | Out-Null .EXAMPLE Test-PsVersion -Verbose | Out-Null .EXAMPLE $result = Test-PsVersion -MinimalMajorVersion 5 -MinimalMinorVersion 1 -Verbose #> function Test-PsVersion { [CmdletBinding(DefaultParameterSetName='Default')] [OutputType([bool])] param( # The minimal PS version required to run the task. [Parameter(ParameterSetName='Version', Mandatory=$true)] [version] $MinimalVersion, # The minimal PS major version to run the task. [Parameter(ParameterSetName='Default')] [int] $MinimalMajorVersion = 5, # The minimal PS minor version to run the task. [Parameter(ParameterSetName='Default')] [int] $MinimalMinorVersion = 0 ) if($MinimalVersion){ if($PSVersionTable.PSVersion -lt $MinimalVersion){ Write-Warning ('PowerShell {0} or higher required to execute this task. Current version is {1}.' -f $MinimalVersion, $PSVersionTable.PSVersion) return $false } } if ($PSVersionTable.PSVersion.Major -lt $MinimalMajorVersion -or ($PSVersionTable.PSVersion.Major -eq $MinimalMajorVersion -and $PSVersionTable.PSVersion.Minor -lt $MinimalMinorVersion)) { Write-Warning ('PowerShell {0}.{1} or higher required to execute this task. Current version is {2}.{3}.' -f $MinimalMajorVersion, $MinimalMinorVersion, $PSVersionTable.PSVersion.Major, $PSVersionTable.PSVersion.Minor) return $false } if($MinimalVersion){ $msg = 'PowerShell version {0} meets the minimal required version {1} to execute this task.' -f $MinimalVersion.ToString(), $PSVersionTable.PSVersion.ToString() } else { $msg = 'PowerShell version {0}.{1} meets the minimal required version {2}.{3} to execute this task.' -f $PSVersionTable.PSVersion.Major, $PSVersionTable.PSVersion.Minor, $MinimalMajorVersion, $MinimalMinorVersion } Write-Verbose $msg return $true } Export-ModuleMember -Function Test-PsVersion |