Monday, October 5, 2009

PowerShell: Conditional Snapins Using Profile.ps1

I redirect My Documents from our office file server to whatever Windows machine I log into. As part of this, my Windows PowerShell Profile.ps1 script is executed. Unfortunately, the snapins referenced in this script aren't necessarily available on the host I am currently logged into. To combat this, I use a conditional statement to check both the computer I'm logged into as well as if the snapin is already loaded.



Additionally, many vendors that develop tools for the PowerShell (including Microsoft), will provide a shortcut that will open a command window with the snapin loaded. Personally, I don't like this. For several reasons, but mainly because I use the PowerShell for more than one thing at a time and I keep it open. I don't want to have to open many different shortcuts to access different tools. With the script below, I can load any or all snapins into my console based on the computer I am currently logged into. This gives me the control that I want to load the snapins based on the computer that I am currently using.

$currenthost = hostname if ((get-pssnapin -name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {if ($currenthost -eq "myLaptop") {add-pssnapin VMware.VimAutomation.Core}}

This script will check if the snapin is already loaded and suppress any errors if it is. Also, it checks for the host I am logged into and loads the appropriate snapin because it is available on my computer.

No comments: