Wednesday, June 2, 2010

Things I learned from the Scripting Games 2010 #2: #Requires

So this post comes from the "how embarrassing" folder.  I've been fiddling with and using PowerShell since it was the Monad beta, and until the scripting games I didn't know about #Requires.  '#Requires' is awesome.  You just stick it at or around the start of your script, and the magic happens.  There's a pretty good summary available in PowerShell if you type:

get-help about_Requires

But this all comes with a bit of a caveat, there isn't an option for #Requires for those nifty new things called modules!  So we can '#Requires -version 2' to require PowerShell version 2, we can '#Requires -PSSnapIn Quest.ActiveRoles.ADManagement' to require the Quest AD snap-in....but we can't '#Requires -Module grouppolicy' to require a module.  Bummer.  So how can we require a module the "hard" way?  Here's one way:

function Test-ModuleAvailability([string]$modulename,[switch]$Import)            
{            
    # Check to see if our module is available            
    [System.Management.Automation.PSModuleInfo]$results = `
          Get-Module -ListAvailable | ? { $_.name -ieq $modulename }            
    if ($results)            
    {            
        if ($Import -and $results.sessionState -eq $null)            
        {            
            #Import the module            
            Import-Module $results            
        }            
        #Return true, the module is available            
        $true            
    }            
    else            
    {            
        #Return false, the module is not available            
        $false            
    }                
}

With this function we can easily test for a module's availability, load it if it we need to, and throw an error if $false is returned:

if (-not $(Test-ModuleAvailability FileSystem -Import))            
{            
    Throw "Could not find or load required Module FileSystem"            
}

Not too hard, but maybe those PowerShell guys will hook us up with a beefed up #Requires statement later.

Until tomorrow!