PowerShell 2.0: One Cmdlet at a Time 72 Export-ModuleMember

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Export-ModuleMember cmdlet.

What can I do with it?

PowerShell 2.0 introduces the concept of modules; essentially they are the evolution of snapins from PowerShell 1.0. Export-ModuleMember specifies elements from a module, like functions or variables, which can be exported. Note: This cmdlet can only be used within a *.psm1 script module file or a dynamic module created with New-Module.

Examples:

Create a new dynamic module using New-Module containing two variables inside the scriptblock. Export only the variable $s2 so that it is available for use. Note: Export-ModuleMember needs to be included inside the scriptblock.

New-Module -ScriptBlock {$s1 = ‘Server1’; $s2 = ‘Server2’; Export-ModuleMember -Variable s2}

You will notice that $s1 is not available in the current session, but $s2 is.

The other area to use this cmdlet is within a *.psm1 script module file.  In the below example by default all functions would be exported if the Export-ModuleMember cmdlet was not used. However, by using the Export-ModuleMember cmdlet we can control which functions are exported and also export aliases.

So in the example below the Write-Logfile and Greet-User functions would be exported, but the Yesterdays-Date function would not. In addition the gu alias would be exported.

How could I have done this in PowerShell 1.0?

This functionality was not avaliable with snapins in PowerShell 1.0

1000 things 1% better