Friday Fun: Create All PowerShell Profile Scripts

talkbubbleWhenever I train on PowerShell I inevitably get around to discussing PowerShell profile scripts. For those of you new to PowerShell, a profile script is where you put all the commands you want to run that will define your PowerShell session just the way you need it. You might load some snapins, create some PSDrives or define some variables. There are actually several profile scripts that can be run, depending on whether you are in the PowerShell console, the PowerShell ISE or some other PowerShell host.

The profile paths are hard-coded. You can see all of them by looking at the built-in $profile variable.

You can also look at just $profile which will show you the script for the current user on the current host. If you look at this in the ISE you’ll see some things are different.

ISE-Profiles

This variable is a bit tricky. Even though you can see properties here, if you pipe $profile to Get-Member all you get is a string definition. Here’s another way you can discover these.

Although I don’t really care about the length so let’s filter it out.

Now for the fun part. That value is a path so I can use Test-Path to see if it exists. If not, I can create the profile and at least indicate that is isn’t being used. Because most of these files don’t exist by default and in fact the WindowsPowerShell folder doesn’t exist under Documents until you create it, you might have to create the parent folder first. So I came up with a little script called Create-AllProfiles.ps1.

The script takes advantage of a feature in PowerShell 3 that will automatically enumerate properties. In PowerShell 2.0 I would need to do this:

But now in v3 and later I can do this:

The value property would show all of the values, including the length so because I’m getting an array, I can use a range of index numbers to select just the ones I want. In my script each value is tested and those that don’t exist are passed on to Foreach-Object.

For each path, I first split it so I can test if the parent path exists. If not, it is created. Then I create some text that will be inserted into each new profile script. The script supports -WhatIf so you can see what it would do before you run it for real.

create-allprofiles

I end up with a profile script that looks like this:

create-allprofiles-2

Ideally, I would recommend you digitally sign the profile scripts, assuming you are using an AllSigned execution policy, so that no changes can be made to these scripts without your knowledge. Just don’t forget to run this in the PowerShell ISE as well. If you have profiles already created, they will be ignored. And should you decide later to take advantage of any of the profile scripts, they are ready for you to edit.

Learn, enjoy and have a great weekend.