Creating "Mini-Modules"

by Dec 31, 2012

Did you know that every PowerShell function can be turned into a script module with just one line of code? To test drive this, open the ISE editor and create a function:

function Get-BIOS
{
  param($ComputerName, $Credential)

  Get-WmiObject -Class Win32_BIOS @PSBoundParameters
}

This function called Get-BIOS will get the computer BIOS information and supports -ComputerName and -Credential for remote access, too. Make sure you run the function and test it.

Next, turn the function into a module:

PS> $name = 'Get-BIOS'
PS> New-Item -Path $home\Documents\WindowsPowerShell\Modules\$name\$name.psm1 -ItemType File -Force `
>> -Value "function $name { $((Get-Item function:\$name).Definition) }"

Just make sure $name contains the name of your function, and you ran your function so it is in memory.

Now why is this conversion important? Because PowerShell 3.0 auto-detects functions in modules! So if you use PowerShell 3.0 and have created the "mini module", open up a new PowerShell and type:

PS> Get-BIOS

Bam! Your function is now available automatically, and you can easily add new functionality.

Twitter This Tip! ReTweet this Tip!