Q&A: What was my PowerShell version, again?
Posted: (EET/GMT+2)
Okay, so you're sitting next to a customer's server, and need to run some PowerShell commands. You check the command specs from the Internet, and notice that a particular command is only available in PowerShell 4.0. Can you run this command or not?
Although you can somewhat predict the PowerShell version from the OS version, this isn't a fool-proof method. Similarly, if you need to check the version number in a script, you need to have a suitable command for it.
There's no "Get-PSVersion" command in PowerShell, but there's one cmdlet that comes close, and two neat variables that you can use.
First, there's the command Get-Host. This command returns information about the PowerShell host, and the returned object contains a property called Version. This is the PowerShell version you are after. For example:
PS C:\Users\jani.jarvinen> get-host Name : ConsoleHost Version : 4.0 InstanceId : 743335e5-ea8e-498e-9826-c9a40b8a7640 UI : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture : fi-FI CurrentUICulture : en-US PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy IsRunspacePushed : False Runspace : System.Management.Automation.Runspaces.LocalRunspace
In addition to the Get-Host cmdlet, you can also directly refer to a global variable called $host. This variable contains the same value as Get-Host would return.
With either Get-Host or $host, you can read the PowerShell's major version number from the property Version.Major.
Finally, there's a somewhat less-known variable called $PSVersionTable. If you query the value of this variable, the results look like this:
PS C:\Users\jani.jarvinen> $psversiontable
Name Value
---- -----
PSVersion 4.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.34014
BuildVersion 6.3.9600.17090
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion 2.2
These results are from a Windows 8.1 machine with the latest updates. Notice how the property called PSVersion gives you the results you need.
Notice also the other useful properties: CLRVersion and PSCompatibleVersionings.