PowerShell Importing a Module
Importing a module loads its commands into your script. It makes the module functions ready to call.
Import a module, then call its function
The script creates the module file first. Import-Module loads it, and Get-Greeting runs.
$modulePath = Join-Path $PSScriptRoot "StringTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Greeting { param([string]$Name) "Hello, $Name" }'
Import-Module $modulePath
Get-Greeting -Name "Ana"One import loads every function
Importing loads the whole module file at once. Both functions below are ready to call after one import.
$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 }'
Import-Module $modulePath
Get-Greeting -Name "Sam"
Add-Numbers -a 3 -b 4Build the import path from PSScriptRoot
Join-Path joins the script folder and the file name. That path works no matter where the script runs from.
$modulePath = Join-Path $PSScriptRoot "MathTools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Double { param([int]$Number) $Number * 2 }'
Import-Module (Join-Path $PSScriptRoot "MathTools.psm1")
Get-Double -Number 6Example
$modulePath = Join-Path $PSScriptRoot "Tools.psm1"
Set-Content -Path $modulePath -Value 'function Get-Greeting { param([string]$Name) "Hello, $Name" }', 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
Import-Module $modulePath
Get-Greeting -Name "Ana"
Add-Numbers -a 6 -b 4Key points
- Import-Module: a command that loads a module file into the current script.
- Path: Join-Path builds a file path from a folder and a file name.
- PSScriptRoot: a built-in variable that holds the folder of the running script.
- Call: after import, you call a module function just like a built-in command.
- Module file: the script must create the module file before it imports it.
In this example, the script builds the module path from the script folder. It writes two functions into the module file. It imports the module. It calls both functions, one after the other.
Note
module functions must use approved verbs, or the import prints a warning.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which command loads a module file into the current script?