MSDN Documentation

PowerShell Module Development

This article provides a comprehensive guide to developing PowerShell modules, from basic concepts to advanced techniques. PowerShell modules are a fundamental way to package and distribute reusable PowerShell commands, functions, and variables. They enhance the extensibility and organization of your PowerShell environment.

What is a PowerShell Module?

A PowerShell module is a package of related PowerShell functionalities. It can contain cmdlets, functions, variables, aliases, and other resources that extend PowerShell's capabilities. Modules allow you to:

Types of PowerShell Modules

PowerShell supports several types of modules:

Creating a Basic Script Module

Let's create a simple script module named "MyModule".

  1. Create a folder for your module, for example, C:\Users\YourUser\Documents\PowerShell\Modules\MyModule.
  2. Inside this folder, create a file named MyModule.psm1.
  3. Open MyModule.psm1 in a text editor and add the following content:

function Get-MyGreeting {
    param(
        [string]$Name = "World"
    )
    "Hello, $Name!"
}

Export-ModuleMember -Function Get-MyGreeting
            

The Export-ModuleMember cmdlet ensures that the Get-MyGreeting function is available when the module is imported.

Creating a Module Manifest

To provide more metadata and control over your module, you can create a module manifest.

  1. In your module folder (e.g., C:\Users\YourUser\Documents\PowerShell\Modules\MyModule), run the following command in PowerShell:

New-ModuleManifest -Path .\MyModule.psd1 -RootModule MyModule.psm1 -Author "Your Name" -Description "A sample module"
            

This will create a MyModule.psd1 file with default settings. You can edit this file to configure module settings like version, required version of PowerShell, and dependencies.

Importing and Using Modules

To use your module, place it in a directory that PowerShell searches for modules. By default, PowerShell searches directories listed in the $env:PSModulePath environment variable.

After placing your module, you can import it using the Import-Module cmdlet:


Import-Module MyModule
            

Once imported, you can use the functions defined in your module:


Get-MyGreeting
Get-MyGreeting -Name "PowerShell Developer"
            

Tip

You can view the cmdlets and functions available in an imported module using Get-Command -Module MyModule.

Best Practices for Module Development

Note

For binary modules, you will need to use Visual Studio or another .NET development environment to compile your C# or F# code into a DLL.

Further Reading

Explore the following resources for more in-depth information: