Prof. Powershell

Snapins on Standby

Find it, load it, and use it, in that order. It's this week's lesson on PowerShell snapins.

In Windows PowerShell 1.0, you can extend a shell's functionality by loading additional cmdlets. These are packaged as PSSnapins and the PSSnapin must be loaded into your PowerShell session before you can use it. You could load all snapins every time you launch PowerShell by adding the necessary lines to your PowerShell profile. But a better approach would be to load them when you need them.

If a PSSnapin has been loaded, the Get-PSSnapin command will show you:

PS C:\> Get-PSSnapin "SDMSoftware.PowerShell.GPMC"

This is looking for the group policy cmdlets from SDMSoftware, written by the GPO Guy, Darren Mar-Elia. If I haven't loaded them I can check to see if they are installed and registered with Powershell:

PS C:\> Get-PSSnapin "SDMSoftware.PowerShell.GPMC" -registered

If they are, I can load them:

PS C:\> Add-PSSnapin "SDMSoftware.PowerShell.GPMC"

What would be nice is a programmatic way to check if a PSSnapin is loaded or registered. Here's a block of code you could use in a script or function:

$snapin="SDMSoftware.PowerShell.GPMC"
if (get-pssnapin $snapin -ea "silentlycontinue") {
write-host "PSsnapin $snapin is loaded"
}
elseif (get-pssnapin $snapin -registered -ea "silentlycontinue") {
write-host "PSsnapin $snapin is registered but not loaded"
Add-PSSnapin $snapin
}
else {
write-host "PSSnapin $snapin not found" -foregroundcolor Red
}

The $snapin variable holds the name of the PSSnapin I want to use. The If construct will return $True if the Get-PSSnapin command is successful. Notice I'm using the common parameter, -ErrorAction, which has an alias of -ea. The SilentlyContinue value instructs PowerShell not to display any error messages or raise an exception. This is fine since I'm going to handle errors myself. If the PSSnapin is found, a message is displayed. If it is not loaded, then I'll use ElseIf to see if the PSSnapin is at least registered. If it is, a message is displayed and the PSSnapin loaded. Otherwise the PSSnapin is not available and a suitable message is displayed.

You may want to comment out the Write-Host lines and simply load the snapin if it is registered but not loaded.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular