Monday, August 12, 2019

Powershell 5, 6, 7 -- Where am I?

So, I'm testing out Powershell Core (6.2.2) and Powershell 7 (7.0.0-preview.2) on a Windows system, and it occurred to me that I might want to know which version I am in while working. This seemed simple enough.

For more information, see the RTPSUG intro to 6.2/7.0 here.

I had already noticed that 6.2 and 7.0 do not use my 5.1 $PROFILE, so why not have the profile change the shell prompt?

function Global:prompt { "PS 5 | $PWD>" }

Add that to my 5.1 profile, and I get:

PS 5 | A:\>

I went to create a profile for 6.2 (basic instructions here), and added:

function Global:prompt { "PS 6 | $PWD>" }

And got:

PS 6 | A:\>

Nice. I then went to 7.0 and I see:

PS 6 | A:\>

Well... It seems that the way I installed 6.2 and 7.0 (or the default manner of the shell) has the two versions sharing a $PROFILE. So, we need to do this the way I should have done from the beginning. I change my two profiles to have the following:

function Global:prompt{ "PS $($PSVersionTable.PSVersion.Major)>" }

$PSVersionTable.PSVersion is a System.Version variable. So now I get the correct major version programmatically.

Although, there is an even better way to handle this...

Here are the two profile locations:

PS 5 | C:\Users\david\bin>$profile
C:\Users\david\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

PS 6 | C:\Users\david\bin>$PROFILE
C:\Users\david\Documents\PowerShell\Microsoft.PowerShell_profile.ps1


I have many functions I use, and variables defined in my 5.1 profile. Do I want to replicate everything, every time? No. So, instead, let's do this to my 6.2/7.0 profile:

$PROFILE = "C:\Users\david\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
. $PROFILE


This re-assigns my 6.2/7.0 $PROFILE value to match that of my 5.2 $PROFILE value. I then dot-source my profile, and my 5.1 profile is loaded into whichever version I use.

No comments: