Weekend Scripter: Build Your Own PowerShell Cmdlet: Part 9 of 9
Summary: Microsoft Windows PowerShell MVP, Sean Kearney, continues a series of guest blogs detailing building your own cmdlet. Microsoft Scripting Guy, Ed Wilson, is here. Guest blogger and Windows PowerShell MVP, Sean Kearney, has written a series about building cmdlets. For more about Sean, see his previous guest blog posts.
Note This is Part 9 of a nine-part series about building your own Windows PowerShell cmdlet. Read the entire series as it unfolded. Here’s Sean with the conclusion…
Working with a module
Perhaps the best and easiest part about having cmdlets of your very own is that you can put them in a module that you can load as you need. To create a module requires nothing more than creating a folder, placing your PS1 file that is used to load the cmdlet within it, and then renaming it as PSM1. So first let’s create folder to hold the module. We can store it anywhere we choose. So we’ll create it within a USB key. For the purposes of this blog, let’s presume it has been assigned the drive letter of G:.
NEW-ITEM –type Directory –path G:HSG –force We can now take the most recent version of our script, and we’ll place it within our module folder.
COPY-ITEM C:PowerShellAddLog.ps1 G:HSGMyFirstModule.psm1 If you created additional cmdlets, the only thing you need to do is copy the contents and paste them into your PSM1 file, continually adding one after another. Your module file is only limited by your imagination. At this point, you can exit your Windows PowerShell console. When you enter it again, you only need to run the Import-Module cmdlet to load up your personal module.
IMPORT-MODULE G:HSG If you would like to see what cmdlets are available in your new module, you run a standard Get-Command cmdlet and specify your module name.
GET-COMMAND –module MyFirstModule Like any other module, you can remove it and its cmdlets from memory by using the Remove-Module cmdlet.
REMOVE-MODULE -module MyFirstModule Of course, the best part of all is that you can now share this module. Simply copy the folder that you created to wherever you need to be, or compress it to email it to coworkers or the rest of the Windows PowerShell community. ~Sean What a wonderful series of guest blogs. Thank you, Sean, for sharing. This has been an especially great series, and one that I will refer to people again, and again, and again… I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at firstname.lastname@example.org, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace. Ed Wilson, Microsoft Scripting Guy