PowerShell 2.0: One Cmdlet at a Time 71 New-Module
Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the New-Module 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. New-Module enables you to create a dynamic module from a script block that is available in the current session.
Note: New-Module does not create a module on disk available for use at a later date! However, Jeffrey Snover has created a module which will create a template for a new module on disk for you.
Examples:
Create a new dynamic module with the Function Write-Logfile as the scriptblock to create the module. Test to see whether the function is available from Get-Module or Get-Command.
New-Module -ScriptBlock {Function Write-Logfile ($log) {$Logfile = “C:\Log.txt”; $log | Out-File -FilePath $Logfile -Append}} Get-Module Get-Command Write-Logfile
You will see that Get-Module is not aware of the new module, but Get-Command is aware of the Write-Logfile function.
Create a new dynamic module with the Function Write-Logfile as the scriptblock to create the module. Give it a name and use Import-Module to make it available to Get-Module. Test to see whether the function is available from Get-Module or Get-Command.
New-Module -ScriptBlock {Function Write-Logfile ($log) {$Logfile = “C:\Log.txt”; $log | Out-File -FilePath $Logfile -Append}} -Name LogfileModule | Import-Module Get-Module Get-Command Write-Logfile
You will see that this time both Get-Module and Get-Command are aware of the LogfileModule and Write-Logfile function.
How could I have done this in PowerShell 1.0?
You could have created a custom snapin and imported with the Add-PSSnapin cmdlet.