Friday, June 21, 2013

Extending PowerShell Commands : Modules




You can load additional commands in PowerShell via Modules.A module is really nothing more than a PowerShell script with a .psm1 file extension, although they can include binary code, typically delivered in a dll file.

Run below command to see modules exiting in your session :

PS > get-module

It is very possible you'll get nothing. But that simply means nothing is loaded in your session. We need to ask PowerShell to tell us what modules are available:

PS > get-module -ListAvailable

User modules are found in ...\Documents\WindowsPowerShell\Modules and system modules in $pshome\Modules. Some products may modify this variable. PowerShell gets this collection of objects by checking an environmental variable:

PS > $env:PSModulePath


When I want to use a module, I can import it. Consider i want to import the HyperV module, execute below command:

PS > Import-Module HyperV

If you have a module file in another folder outside of $env:PSModulePath, you can still import it if you specify the path:

PS > import-module S:\PSVirtualBox

To discover what the module can do, we can ask the Get-Command cmdlet:

PS > get-command -Module HyperV

CommandType   Name                 Definition
-----------   ----                 ----------
Alias         Add-NewVMHardDisk    Add-VMNewHardDisk
Function      Add-VMDisk           # .ExternalHelp MAML-VMDisk...
Function      Add-VMDrive          # .ExternalHelp MAML-VMDisk...
Function      Add-VMFloppyDisk     # .ExternalHelp MAML-VMDisk...
Function      Add-VMKVP            # .ExternalHelp MAML-VMConf...
...

I can use any of these commands as long as the module is loaded in my PowerShell session. Once I close my session the module is removed. If I want to always have this module available, I simply add the Import-Module command to my PowerShell profile. If you want to unload a module manually, you can do this:

PS C:\> Remove-Module HyperV


No comments:

Post a Comment