Tuesday, January 23, 2018

PowerShell Version Check

Sometimes, certain PowerShell scripts or commands require a particular version of PowerShell to be installed. A command that works just fine with, say, version 3 will throw an error if using version 2.

One way to prevent the error is to first check which version is available. We can develop logic to conduct one action or another, depending on the version:

   $PSVersion = $PSVersionTable.PSVersion.Major 

Here we created a variable called $PSVersion and made it equal to the Major PowerShell version, using dot notation to get just the relevant number:

 

Now we can use this variable in an if...else statement to decide on a course of action:

    if ($PSVersion -eq 4) {
        Write-Output "Your PowerShell version is $PSVersion. `

        The script should work fine."
    } else {
        Write-Output "Your PowerShell needs to be updated for `

        this script to work properly."
    }



First we used the if command to check to see if the variable $PSVersion is equal to (or '-eq' for short) the number '4'. If it is, then the Write-Output command within the first pair of braces is executed. If the variable is equal to anything else, then the command with the second pair of braces is executed. 

This would be a useful set of commands to add to the beginning of a script to inform the user if their version of PowerShell will be suitable.
 

No comments:

Post a Comment