Powershell

How to Write a PowerShell Script Module

Microsoft created PowerShell, a flexible and potent tool for automating processes and controlling system settings. The PowerShell “script modules” enhance its functionality by allowing the encapsulation of related functions, cmdlets, and scripts for seamless reusability. Writing a PowerShell script module can greatly enhance the productivity and efficiency of managing tasks in the Microsoft environment.

In this article, we will explore the fundamental steps required to create a robust and reusable “PowerShell script module”, demonstrating a comprehensive understanding of the subject matter.

Create a Module Manifest File

A well-structured PowerShell Script Module begins with defining a clear purpose or objective. Each module should contain a “manifest file (.psd1)” to specify metadata about the module. It is essential to meticulously organize the module’s scripts, functions, and cmdlets in separate files, arranging them logically within a module folder.

Create a PowerShell Script

To create a script module, save a precise “PowerShell script” to a “.psm1” file. The name of the script and the directory where it is saved must match.

The directory for the module must be in the path designated by “$env:PSModulePath”. Any resources required to execute the script can be found in the module’s directory, along with a module manifest file

explaining how your module functions to PowerShell.

Defining Functions and Cmdlets

To create functions within the module, utilize the “function” keyword followed by a meaningful name that adheres to the PowerShell’s naming conventions. Consider utilizing parameters to enhance flexibility and usability.

Additionally, documentation comments “(‘<# … #>’)” for both functions and cmdlets facilitate understanding and enable the generation of help documentation.

Create individual “.psm1” files for each function within the Public or Private folders, depending on their intended use. For example, let’s create a function “Func1” specifying the stated Mandatory parameters:

function Func1 {
    param (
        [Parameter(Mandatory)]
        [string] $Name,
        [Parameter(Mandatory)]
        [string] $Location
    )

 

Exporting a Function

Module developers can make their created functions available to the user by either exporting them explicitly or using a wildcard character (*). Use “Export-ModuleMember” to limit user’s access to specific functions or variables at the end of your script, as follows:

function Func1 {
}
Export-ModuleMember -Function Func1

 

Importing in a PowerShell Session

After creating the module, you can import it into your PowerShell session or other scripts to execute its functions. Here’s an example/syntax of how to import and use the functions from the module:

Import-Module -Name <ModuleName>

 

Note: The “$env:PSModulePath” global variable contains the paths where your module can be installed. Despite the fact that your module only has one “.psm1” file, make sure to name the directory you create for it with the same name as the script module.

You would need to specify “Import-Module” to find your module if you didn’t save it in one of these locations. Otherwise, the module wouldn’t be discoverable by PowerShell.

Writing a PowerShell Script Module

The following steps discuss the procedure to write a “PowerShell Script Module”:

Step 1: Create a Module Directory

Create a new directory “MyMod” (in this case) to contain your PowerShell script module:

Step 2: Create the Module Manifest File

Now, create a new “MyMod.psd1” (the module manifest) file in the “MyMod” directory. Your module’s metadata can be found in this file. Open a text editor and enter the following information:

@{
    ModuleVersion = '1.0.0.0'
    RootModule = 'MyMod.psm1'
    CompatiblePSEditions = 'Desktop'
    GUID = 'Your-Generated-GUID'
    Author = 'Your Name'
    Description = 'Description of your module'
}

 

Note: Use a different identification to replace “Your-Generated-GUID” (you can create one by using the “New-GUID” cmdlet) as follows:

New-GUID

 

Step 3: Create the Module Script

Create a new file named “MyMod.psm1” (the module script) in the “MyMod” directory. Your module’s functionality will be contained in this file:

Now, open the “MyMod.psm1” file in a text editor and enter the following information:

function Get-Hello {
    Write-Output 'Hello, Linuxhint!'
}

 

This function “Get-Hello” returns the message “Hello, Linuxhint!“.

Step 4: Import and Use the Module

To use the module, open a PowerShell session and execute these commands:

Import-Module -Name 'path\to\MyModule'

 

In this command, the path “path\to\MyModule” is replaced with the actual path to the “MyMod” directory, as follows:

Now, execute the function mentioned in the module:

Get-Hello

 

The “Hello, Linuxhint!” message is displayed when you run the “Get-Hello” command as it calls the function specified in the module script.

Conclusion

Writing a “PowerShell Script Module” involves thoughtful planning, technical proficiency, and adherence to best practices. It requires creating a module directory, module manifest file, module script, and lastly, importing and using the module. By doing so, users can deliver high-quality modules that exemplify intelligence and comprehension.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.