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.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Basically, my profile script checks the version first, before doing anything. You can use the $psversiontable variable.
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.
#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.
This is great, though personally I am not doing anything in my profile that would need this other than pre-loading a vendor’s module/snapin. Is there anything you are doing that takes advantage of this? I am really curious about what people do to make their profiles better.
Yes I do. I use the new PSDefaultParameterValues feature. I also load some functions that use 3.0 specific features like ordered hashtables.