One of the best things about PowerShell 3.0, for me anyway, is the ability to run PowerShell 2.0 side by side. I often need to test commands and scripts in both versions not only for my writing projects but also when helping people out. Like many of you I have a PowerShell profile script that configures my console. And because I primarily use PowerShell 3.0 I tend to have a number of version specific commands in my profile. The problem is that when I launch a PowerShell 2.0 session it uses the same profile, resulting in error messages for things it can’t do. So this is how I handle having a single profile that can be used by two different versions of PowerShell.
Basically, my profile script checks the version first, before doing anything. You can use the $psversiontable variable.
|
1 2 3 4 5 6 7 8 9 10 11 |
PS C:\> $PSVersionTable Name Value ---- ----- PSVersion 3.0 WSManStackVersion 3.0 SerializationVersion 1.1.0.1 CLRVersion 4.0.30319.18033 BuildVersion 6.2.9200.16434 PSCompatibleVersions {1.0, 2.0, 3.0} PSRemotingProtocolVersion 2.2 |
The PSVersion property is what I’m looking for. With this information, I can wrap my PowerShell profile script in simple IF statement.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#requires -version 2.0 <# Use code like this in your PowerShell profile if it will be shared between PowerShell 2 and PowerShell 3 sessions on the same computer #> if ($psversiontable.psversion -eq '3.0') { Write-Host "You are running PowerShell 3.0" -ForegroundColor Green #insert 3.0 specific commands $PSDefaultParameterValues.Add("Format-Table:Autosize",$True) } else { Write-Host "You are running PowerShell 2.0" -ForegroundColor Yellow #insert 2.0 specific commands } #insert commands that apply to both versions |
I think the comments in the code sample are pretty clear and there’s really not much else to add. The Write-Host lines are merely for testing. You don’t really need them.
Now I can get properly configured PowerShell sessions regardless of version and without errors.



