Run a powershell script if the computer contains the correct powershell version

Several times I encountered that a computer I was running my scipt on, didn’t support a certain parameter or a certain command because it didn’t have Powershell 4 installed. Thus I thought it would be time to create a default error-handling for each of my scripts which checks if the computer runs the correct Powershell version.
Since I mostly use powershell 4 on my own systems, I created this check for this version.

If ($PSVersionTable.PSVersion.Major -ge 4)
{
# Enter PS 4.0 code here
Write-Host("Your powershell version is 4.0")
}
Else
{
# Enter code here
Write-Error("You need at least Powershell 4.0 to run this program. Powershell is part of the Windows Management Framework and can be downloaded here: http://www.microsoft.com/en-us/download/details.aspx?id=40855") -Category NotInstalled -ErrorId "PSVersion < 4.0"
}

This way you can be sure the code will only run if Powershell 4 or higher is installed. If not, it’ll display an error message with a download link.

You can also just add this to the top of your script:

#Requires –Version 4.0

Now the script will only run if ran on v 4 of Powershell. But it’ll only give you an error and won’t give you the download link. So in my case I thought the first solution is better, in case I share scripts with colluagues who don’t have Powershell 4 installed yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s