Tuesday, September 20, 2011

PowerShell V3 - Autoloading Modules

Autoloading is a cool feature in PowerShell V3. With Autoloading, PowerShell allows you to ‘see’ cmdlets included in module without you needing to explicitly loading the relevant module. And when you need to run the cmdlet, the module is loaded automatically by PowerShell.

For example, if you run Get-Module on a newly opened PowerShell V3.0 CTP1 prompt, you get the following:

PSH [C:\foo]: get-module

ModuleType Name ExportedCommands
---------- ---- ----------------
Manifest Microsoft.PowerShell.Core {Add-History, Add-PSSnapin, Clear-History, Connect-PSSession...}
Manifest Microsoft.PowerShell.M... {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest Microsoft.PowerShell.U... {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

 

if you then run a cmdlet contained in a module (e.g. Get-CimInstance), then re-run the Get-Module, you see the relevant module has been autoloaded, like this:

PSH [C:\foo]: Get-CimInstance win32_bios
SMBIOSBIOSVersion : A05
Manufacturer      : Dell Inc.
Name              : Default System BIOS
SerialNumber      : 804HWM1
Version           : DELL   - 6222004

PSH [C:\foo]: get-module

ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Manifest   CimCmdlets                {Get-CimAssociatedInstance, Get-CimClass, Get-CimInstance, Get-CimSessio...
Manifest   Microsoft.PowerShell.Core {Add-History, Add-PSSnapin, Clear-History, Connect-PSSession...}
Manifest   Microsoft.PowerShell.M... {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   Microsoft.PowerShell.U... {Add-Member, Add-Type, Clear-Variable, Compare-Object...}

As you can see, PowerShell automatically loaded the new CimCmdlets module as needed. This is a neat feature.

One proviso  - autoloading does not appear to work with script modules. Sad smile

1 comment:

cmcknz77 said...

A question - how does one turn it off? I forsee issues with 'naming conflicts' for example, both the HyperV and VMWare modules/snapins have a Get-VM cmdlet and I'm begging to bet that there'll be no auto-prefixing...

And I can see commands getting blatted especially in 'customer generated script modules/functions' where we 'may not adhere absolutely to the letter of the 'PowerShell best practice function/script/cmdlet naming strategy'...

I do hope there's a Preference variable?