owerShell modules provide a way to organize and package your PowerShell code for better reusability and maintainability. In this guide, we'll walk through the process of creating a simple PowerShell module, exporting cmdlets, and accessing module information.

Step 1: Module Structure

Let's start by creating a basic structure for our module. We'll have a module manifest file (PSD1) and a script module file (PSM1).

MyModule.psd1

# MyModule.psd1

@{
    ModuleVersion = '1.0.0.0'
    Author = 'YourName'
    Description = 'A simple PowerShell module example'
    RootModule = 'MyModule.psm1'
}

MyModule.psm1

# MyModule.psm1

function Get-Greeting {
    Write-Output 'Hello, this is a greeting from MyModule!'
}

Without the usage of Export-ModuleMember all the members are exported. Thus in this initial version of the module the Get-Greeting cmdlet is exported.

Step 2: Cmdlet in a Separate File

You may want to organize your cmdlets in a separate PS1 file within the module. Let's create a file named Cmdlets.ps1 to hold our Get-Double cmdlet.

Cmdlets.ps1

# Cmdlets.ps1

function Get-Double {
    param (
        [int]$Number
    )

    $result = $Number * 2
    Write-Output "Double of $Number is $result"
}

Update the main module file to dot-source this file:

MyModule.psm1

# MyModule.psm1

# Dot-source the separate PS1 file containing cmdlets
. $PSScriptRoot\Cmdlets.ps1

function Get-Greeting {
    Write-Output 'Hello, this is a greeting from MyModule!'
}

# Export the cmdlet
Export-ModuleMember -Function Get-Double

In this update with the usage of Export-ModuleMember cmdlet this makes Get-Greeting cmdlet private.

Step 3: Using the Module

Now, let's use our module in a PowerShell session.

  1. Navigate to the directory containing the "MyModule" folder.

  2. Import the module:

    Import-Module .\MyModule
  3. Use the exported cmdlet:

    Get-Double -Number 5
  4. Use other functions within the module:

    Get-Greeting

Step 4: Accessing Module Information

To access information about the loaded module, use the Get-Module cmdlet:

# Import the module (if not already imported)
Import-Module .\MyModule

# Get information about the module
$moduleInfo = Get-Module -Name MyModule

# Display module information
$moduleInfo

You can also access specific properties:

# Access specific properties
$moduleName = $moduleInfo.Name
$moduleVersion = $moduleInfo.Version
$moduleAuthor = $moduleInfo.Author

# Display specific properties
Write-Output "Module Name: $moduleName"
Write-Output "Module Version: $moduleVersion"
Write-Output "Module Author: $moduleAuthor"

With these steps, you've created a simple PowerShell module, exported a cmdlet, and learned how to access module information. This modular approach can greatly enhance the organization and reusability of your PowerShell scripts and functions. Happy scripting!