In this tutorial, I will explain how to create a PowerShell module, which allows you to organize and reuse your PowerShell code in a modular way. PowerShell modules enable you to partition, organize, and abstract your PowerShell code into self-contained, reusable units.
What is a PowerShell Module?
A PowerShell module is a package containing PowerShell functions, variables, and other resources that can be loaded and used in your PowerShell scripts. Modules make it easy to share and distribute your code, as well as improve the organization and maintainability of your PowerShell projects.
Why Create a PowerShell Module?
Now, let me explain why we need to create a PowerShell module.
Imagine you work for a company that manages multiple servers. You find yourself writing similar PowerShell scripts to manage Active Directory users, monitor system performance, and generate reports. Instead of copying and pasting code between scripts, you can create a PowerShell module that encapsulates these common functions and reuse them across your projects.
Check out Create and Use Dictionaries in PowerShell
Create a PowerShell Module
Now, let me show you how to create a PowerShell module step by step.
Step 1: Plan Your Module
Before diving into creating a module, it’s important to plan out its structure and functionality. Consider the following:
- What functions will your module include?
- How will you organize these functions into files?
- What will you name your module?
For this example, let’s say we want to create a module called “ServerManagement” that includes functions for managing Active Directory users and generating server performance reports.
Step 2: Create the Module Directory and Files
To create a script module, save a valid PowerShell script to a .psm1 file. The script and the directory where it’s stored must use the same name.
- Create a new directory named “ServerManagement” to store your module files.
- Inside the “ServerManagement” directory, create a file named “ServerManagement.psm1”. This will be your main module file.
- Create additional .ps1 files for each function you want to include in your module. For this example, let’s create two files: “AdUserManagement.ps1” and “PerformanceReporting.ps1”.
Read Create a Registry Key with PowerShell If It Does Not Exist
Step 3: Write Your Functions
Open the “AdUserManagement.ps1” file and add the following function:
function New-AdUser {
param(
[string]$FirstName,
[string]$LastName,
[string]$Department
)
$FullName = "$FirstName $LastName"
$Username = ($FirstName[0] + $LastName).ToLower()
$Email = "$Username@contoso.com"
New-ADUser -Name $FullName -GivenName $FirstName -Surname $LastName -UserPrincipalName $Username -EmailAddress $Email -Department $Department -Enabled $true
}This function creates a new Active Directory user with the provided first name, last name, and department.
Next, open the “PerformanceReporting.ps1” file and add the following function:
function Get-ServerPerformanceReport {
param(
[string[]]$ServerNames
)
foreach ($ServerName in $ServerNames) {
$CpuUsage = Get-WmiObject -Class Win32_Processor -ComputerName $ServerName | Measure-Object -Property LoadPercentage -Average | Select-Object -ExpandProperty Average
$MemoryUsage = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ServerName | Select-Object @{Name="MemoryUsage"; Expression={"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory) * 100) / $_.TotalVisibleMemorySize)}}
[PSCustomObject]@{
ServerName = $ServerName
CpuUsage = "$CpuUsage%"
MemoryUsage = "$($MemoryUsage.MemoryUsage)%"
}
}
}This function retrieves CPU and memory usage for the specified servers and returns a custom object with the results.
Read Create a Hashtable in PowerShell
Step 4: Create the Module Manifest
A module manifest is a .psd1 file that contains metadata about your module, such as its version, author, and exported functions.
- In the “ServerManagement” directory, create a file named “ServerManagement.psd1”.
- Open the “ServerManagement.psd1” file and add the following content:
@{
RootModule = 'ServerManagement.psm1'
ModuleVersion = '1.0'
Author = 'John Doe'
Description = 'A module for managing servers and Active Directory users'
FunctionsToExport = @('New-AdUser', 'Get-ServerPerformanceReport')
}Make sure to update the author and description fields with your own information.
Step 5: Import Functions into the Main Module File
Open the “ServerManagement.psm1” file and add the following lines to import the functions from the other .ps1 files:
. $PSScriptRoot\AdUserManagement.ps1
. $PSScriptRoot\PerformanceReporting.ps1Step 6: Install and Use Your Module
To install your module, copy the “ServerManagement” directory to one of the PowerShell module paths. You can find the module paths by running $env:PSModulePath.
Once installed, you can import your module in a PowerShell session using the following command:
Import-Module ServerManagementNow you can use the functions from your module:
New-AdUser -FirstName "John" -LastName "Smith" -Department "IT"
Get-ServerPerformanceReport -ServerNames "Server1", "Server2"Conclusion
In this tutorial, I explained how to create a PowerShell module to manage Active Directory users and generate server performance reports. By organizing your code into modules, you can improve your PowerShell scripts’ reusability, maintainability, and shareability.
You may also like:
- Enable PowerShell Logging
- Get Windows Event Logs using PowerShell
- Retrieve Your Windows Product Key Using PowerShell
- Create a Credential Object in PowerShell
- How to Keep Your Screen Active with a PowerShell Script?
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.