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.

Tags: , ,

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: