PowerShell Writing a Module
A module is a file that holds reusable commands. It lets you share functions between scripts without copying them.
A module file ends in .psm1
Set-Content writes one function into a module file. Test-Path then checks that the file exists.
$modulePath = Join-Path $PSScriptRoot "GreetTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Greeting { param([string]$Name) "Hello, $Name" }'
Test-Path $modulePathOne module can hold two functions
Set-Content accepts more than one line of text. Each line becomes one function in the module file.
$modulePath = Join-Path $PSScriptRoot "StringTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Greeting { param([string]$Name) "Hello, $Name" }', 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
Get-Content -Path $modulePathCount the functions in a module file
Get-Content reads the module file back. Its Count tells how many lines the file holds.
$modulePath = Join-Path $PSScriptRoot "MathTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Double { param([int]$Number) $Number * 2 }', 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
(Get-Content -Path $modulePath).CountExample
$modulePath = Join-Path $PSScriptRoot "MathTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Double { param([int]$Number) $Number * 2 }', 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
Get-Content -Path $modulePath
Test-Path $modulePathKey points
- Module: a file with the .psm1 ending that holds functions.
- Function: a named block of commands you can call again.
- File ending: a module file ends in .psm1, not .ps1.
- Set-Content: a command that writes text lines to a file.
- Approved verb: a module function name starts with an approved verb such as Get or Add.
- One file: one module file can hold more than one function.
In this example, the script builds the module path from the script folder. It writes two functions into the module file. It reads the file back to show both functions. It checks that the file exists.
Note
a module does nothing on its own until another script imports it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What file ending does a PowerShell module use?