January 21st, 2010

Hey, Scripting Guy! Can You Give All the Steps for Creating, Installing, and Using Windows PowerShell Modules?

Bookmark and Share

  Hey, Scripting Guy! Question

Hey, Scripting Guy! I am still a bit confused about how modules work. Could you give a beginning-to-end scenario and go through the steps of creating a module, installing the module, and then using the module?

— SL

 

Hey, Scripting Guy! AnswerHello, SL.

Microsoft Scripting Guy Ed Wilson here. I am sipping a cup of organic tea that is grown in Hawaii. It is lightly infused with a strawberry flavor. I do not normally care for infused flavored teas. I prefer natural tea and natural flavors. However, this tea has a nice bouquet with a hint of fruit on the palate with a subtle finish. It goes well with the oatmeal, apple, and walnut cookies the Scripting Wife made. She uses extra apples for a natural sweetness in her own recipe that does not call for any flour or sugar. Instead of flour, she used crushed walnuts. How about that? A totally healthy cookie. I enjoy drinking Hawaii tea, particular when it is cold outside. I close my eyes, and I feel a mountain breeze. I can hear the roar of the waterfall. I am on Kauai with my laptop, writing a Windows PowerShell script and enjoying the Wailua Falls:

Image of Wailua Falls

 

SL, let us start at the beginning. The first thing you will probably want to do is create a module. You can create a module in the Windows PowerShell ISE. One of the first things to do is to locate a couple of functions you wish to store in the module; you can copy them directly into the Windows PowerShell ISE, as seen in this image.

Image of functions in Windows PowerShell ISE

 

After you have copied your functions into the new module, save the module with the .PSM1 extension. The basicFunctions.psm1 module is seen here.

BasicFunctions.psm1

Function Get-OptimalSize
{
 <#
  .Synopsis
    Converts Bytes into the appropriate unit of measure.
   .Description
    The Get-OptimalSize function converts bytes into the appropriate unit of
    measure. It returns a string representation of the number.
   .Example
    Get-OptimalSize 1025
    Converts 1025 bytes to 1.00 KiloBytes
    .Example
    Get-OptimalSize -sizeInBytes 10099999
    Converts 10099999 bytes to 9.63 MegaBytes
   .Parameter SizeInBytes
    The size in bytes to be converted
   .Inputs
    [int64]
   .OutPuts
    [string]
   .Notes
    NAME:  Get-OptimalSize
    AUTHOR: Ed Wilson
    LASTEDIT: 1/4/2010
    KEYWORDS:
   .Link
     Http://www.ScriptingGuys.com
 #Requires -Version 2.0
 #>
[CmdletBinding()]
param(
      [Parameter(Mandatory = $true,Position = 0,valueFromPipeline=$true)]
      [int64]
      $sizeInBytes
) #end param
 Switch ($sizeInBytes)
  {
   {$sizeInBytes -ge 1TB} {“{0:n2}” -f  ($sizeInBytes/1TB) + ” TeraBytes”;break}
   {$sizeInBytes -ge 1GB} {“{0:n2}” -f  ($sizeInBytes/1GB) + ” GigaBytes”;break}
   {$sizeInBytes -ge 1MB} {“{0:n2}” -f  ($sizeInBytes/1MB) + ” MegaBytes”;break}
   {$sizeInBytes -ge 1KB} {“{0:n2}” -f  ($sizeInBytes/1KB) + ” KiloBytes”;break}
   Default { “{0:n2}” -f $sizeInBytes + ” Bytes” }
  } #end switch
  $sizeInBytes = $null
} #end Function Get-OptimalSize

Function Get-ComputerInfo
{
 <#
  .Synopsis
    Retrieves basic information about a computer.
   .Description
    The Get-ComputerInfo cmdlet retrieves basic information such as
    computer name, domain name, and currently logged on user from
    a local or remote computer.
   .Example
    Get-ComputerInfo
    Returns comptuer name, domain name and currently logged on user
    from local computer.
    .Example
    Get-ComputerInfo -computer berlin
    Returns comptuer name, domain name and currently logged on user
    from remote computer named berlin.
   .Parameter Computer
    Name of remote computer to retrieve information from
   .Inputs
    [string]
   .OutPuts
    [object]
   .Notes
    NAME:  Get-ComputerInfo
    AUTHOR: Ed Wilson
    LASTEDIT: 1/11/2010
    KEYWORDS:
   .Link
     Http://www.ScriptingGuys.com
 #Requires -Version 2.0
 #>
 Param([string]$computer=”localhost”)
 $wmi = Get-WmiObject -Class win32_computersystem -ComputerName $computer
 $pcinfo = New-Object -TypeName system.object
 $pcInfo | Add-Member -MemberType noteproperty -Name host -Value $($wmi.DNSHostname)
 $pcInfo | Add-Member -MemberType noteproperty -Name domain -Value $($wmi.Domain)
 $pcInfo | Add-Member -MemberType noteproperty -Name user -Value $($wmi.Username)
 $pcInfo
}

You can control what is exported from the module by creating a manifest. If you place related functions that you will more than likely want to use together, you can avoid creating a manifest. In the BasicFunctions.psm1 module, there are two functions, one of which was created during Microsoft Visio Week.

The Get-ComputerInfo function was written for today’s Hey, Scripting Guy! post and is used to return a custom object that contains information about the user, computer name, and computer domain. After you have created and saved the module, you will need to install the module. You can do this manually by navigating to the module directory, creating a folder for the module, and placing a copy of the module in the folder. I prefer to use the Copy-Modules.ps1 script that was discussed on Tuesday.

After the module has been copied to its own directory, you can use the Import-Module cmdlet to import it into the current Windows PowerShell session. If you are not sure of the name of the module, you can use the Get-Module cmdlet with the –ListAvailable switch, as seen here:

PS C:> Get-Module -ListAvailable

ModuleType Name                      ExportedCommands
———- —-                      —————-
Script     BasicFunctions            {}
Script     DotNet                    {}
Manifest   FileSystem                {}
Manifest   IsePack                   {}
Manifest   PowerShellPack            {}
Manifest   PSCodeGen                 {}
Manifest   PSImageTools              {}
Manifest   PSRSS                     {}
Manifest   PSSystemTools             {}
Manifest   PSUserTools               {}
Manifest   TaskScheduler             {}
Manifest   WPK                       {}
Manifest   ActiveDirectory           {}
Manifest   AppLocker                 {}
Manifest   BitsTransfer              {}
Manifest   FailoverClusters          {}
Manifest   GroupPolicy               {}
Manifest   NetworkLoadBalancingCl… {}
Manifest   PSDiagnostics             {}
Manifest   TroubleshootingPack       {}

After you have imported the module, you can use the Get-Command cmdlet with the –module parameter to see which commands are exported by the module. This is illustrated in the following image.

Image of using Get-Command cmdlet with -module parameter

 

After you have added the functions from the module, you can use them directly from the Windows PowerShell prompt. Using the Get-ComputerInfo function is illustrated here:

PS C:> Get-ComputerInfo

host                                    domain                                  user
—-                                    ——                                  —-
mred1                                   NWTraders.Com                           NWTRADERSed

PS C:> (Get-ComputerInfo).user
NWTRADERSed
PS C:> (Get-ComputerInfo).host
mred1
PS C:> Get-ComputerInfo -computer win7-pc | Format-Table -AutoSize

host    domain        user
—-    ——        —-
win7-PC NWTraders.Com NWTRADERSAdministrator

PS C:>

Because the help tags were used when creating the functions, you can use the Get-Help cmdlet to obtain information about using the function. In this manner, the function that was created in the module behaves exactly like a regular Windows PowerShell cmdlet. This includes tab expansion.

PS C:> Get-Help Get-ComputerInfo

NAME
    Get-ComputerInfo

SYNOPSIS
    Retrieves basic information about a computer.

SYNTAX
    Get-ComputerInfo [[-computer] <String>] [<CommonParameters>]

DESCRIPTION
    The Get-ComputerInfo cmdlet retrieves basic information such as
    computer name, domain name, and currently logged on user from
    a local or remote computer.

RELATED LINKS
    Http://www.ScriptingGuys.com
    #Requires -Version 2.0

REMARKS
    To see the examples, type: “get-help Get-ComputerInfo -examples”.
    For more information, type: “get-help Get-ComputerInfo -detailed”.
    For technical information, type: “get-help Get-ComputerInfo -full”.

PS C:> Get-Help Get-ComputerInfo -Examples

NAME
    Get-ComputerInfo

SYNOPSIS
    Retrieves basic information about a computer.

    ————————– EXAMPLE 1 ————————–

    C:PS>Get-ComputerInfo

    Returns comptuer name, domain name and currently logged on user
    from local computer.

    ————————– EXAMPLE 2 ————————–

    C:PS>Get-ComputerInfo -computer berlin

    Returns comptuer name, domain name and currently logged on user
    from remote computer named berlin.

PS C:>

The Get-OptimalSize function can even receive input from the pipeline, as shown here:

PS C:> (get-WmiObject win32_volume -Filter “driveletter = ‘c:'”).freespace

26513960960

PS C:> (get-WmiObject win32_volume -Filter “driveletter = ‘c:'”).freespace | Get-OptimalSize

24.69 GigaBytes

PS C:>

Pretty cool, huh? Okay, SL, here are the steps:

1.     Place functions into a module, and save it with a .psm1 extension.

2.     Copy the module to the modules directory. Use the Copy-Modules.ps1 script to do this.

3.     Obtain a list of available modules by using the Get-Modules cmdlet with the –listavailable switched parameter.

4.     Import modules into your current Windows PowerShell session by using the Import-Module cmdlet.

5.     See which commands are available from the module by using the Get-Command cmdlet with the –module parameter.

6.     Use the Get-Help cmdlet to obtain information about the exported functions.

7.     Use the functions like you would use any other cmdlet.

 

SL, that is all there is to installing and using a Windows PowerShell module. And this concludes Windows PowerShell Module Week. Join us tomorrow for Quick-Hits Friday.

If you want to know exactly what we will be discussing tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to us at scripter@microsoft.com or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

  Ed Wilson and Craig Liebendorfer, Scripting Guys

 

 

Author

0 comments

Discussion are closed.