Scripts, Scope, and Modules
Turn PowerShell functions into scripts and versioned modules: param blocks, $PSScriptRoot, scopes and dot-sourcing, manifests, autoloading and the PowerShell Gallery.
By The Dark DebuggerUpdated 28 min read
This article is about packaging. You'll turn code into .ps1 scripts that take parameters
and find their own files, learn how PowerShell's scopes decide which variables a function
can see, and build a versioned module with a manifest that loads automatically. It assumes
you can write advanced functions. The next
article, error handling, makes these scripts
robust enough to run unattended.
Why packaging matters
Here's how a team's PowerShell usually grows. One person writes a handy Write-Log function.
It gets pasted into five scripts. Someone fixes a bug in two of the copies. A new hire copies
the oldest, buggiest version into a sixth script. Meanwhile a scheduled task fails at 3 a.m.
because a script that loads settings.psd1 from the current directory was started from
C:\Windows\System32.
Scripts that locate their own files, and modules that hold one shared copy of each function with a version number, prevent all of that. Modules are also how you install other people's tools from the PowerShell Gallery. You'll use the same mechanics in both directions.
All examples were saved as files and run with pwsh -NoProfile -File on PowerShell 7.6.9
(Linux), so error messages include a script path and line number. Windows PowerShell 5.1
differences are called out where they exist.
Scripts with a param block
A script is a .ps1 file. Anything you can type at the prompt can go in one, and it can
start with the same [CmdletBinding()] and param() block as an advanced function. This
report script counts error lines in every log under a folder. It reads its settings from a
report-settings.psd1 file that lives next to the script:
#Requires -Version 7.0
<#
.SYNOPSIS
Counts error lines in each log file under -LogPath.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$LogPath
)
$settingsFile = Join-Path -Path $PSScriptRoot -ChildPath 'report-settings.psd1'
$settings = Import-PowerShellDataFile -Path $settingsFile
Write-Verbose "PSScriptRoot: $PSScriptRoot"
Write-Verbose "PSCommandPath: $PSCommandPath"
Write-Verbose "Location: $PWD"
foreach ($file in Get-ChildItem -Path $LogPath -Filter $settings.Filter) {
$levels = foreach ($line in Get-Content -Path $file.FullName) { ($line -split ' ')[1] }
[pscustomobject]@{
Log = $file.Name
Lines = @($levels).Count
Errors = @($levels | Where-Object { $_ -in $settings.ErrorLevels }).Count
}
}The settings file is a PowerShell data file: a single hashtable literal, which
Import-PowerShellDataFile reads safely, without running any code:
@{
Filter = '*.log'
ErrorLevels = @('ERROR', 'FATAL')
}The script is saved as tools/Export-LogReport.ps1. Running it from the project folder:
./tools/Export-LogReport.ps1 -LogPath ./logsLog Lines Errors
--- ----- ------
api.log 4 1
billing.log 3 2And from a completely different folder, with -Verbose:
Set-Location -Path ./elsewhere
../tools/Export-LogReport.ps1 -LogPath ../logs -VerboseVERBOSE: PSScriptRoot: /home/sid/modules/tools
VERBOSE: PSCommandPath: /home/sid/modules/tools/Export-LogReport.ps1
VERBOSE: Location: /home/sid/modules/elsewhere
Log Lines Errors
--- ----- ------
api.log 4 1
billing.log 3 2This is the point of $PSScriptRoot. It is always the folder containing the running
script, wherever the caller happens to be, so the settings file was found both times. Had the
script used a relative path like ./report-settings.psd1, the second run would have looked
in elsewhere/ and failed. That's the 3 a.m. scheduled-task failure from the introduction.
$PSCommandPath is the script's full path, which is useful in log messages. Both variables
work in Windows PowerShell 3.0 and later.
Two rules for running scripts:
-
Use a path, even for the current folder. PowerShell won't run scripts from the current directory by bare name, which protects you from a planted
ls.ps1:Set-Location -Path ./tools Export-LogReport.ps1 -LogPath ../logsExport-LogReport.ps1: /home/sid/modules/run-bare.ps1:2 Line | 2 | Export-LogReport.ps1 -LogPath ../logs | ~~~~~~~~~~~~~~~~~~~~ | The term 'Export-LogReport.ps1' is not recognized as a name of a cmdlet, | function, script file, or executable program. Check the spelling of the | name, or if a path was included, verify that the path is correct and try | again.Write
./Export-LogReport.ps1instead. From outside PowerShell, for example cron, Task Scheduler or CI, callpwsh -NoProfile -NonInteractive -File /path/to/script.ps1 -LogPath …. -
Declare what the script needs.
#Requireslines are checked before anything runs. Asking for a version that isn't there fails cleanly:#Requires -Version 8.0 'This line never runs on PowerShell 7'./needs-v8.ps1: /home/sid/modules/run-requires.ps1:1 Line | 1 | ./needs-v8.ps1 | ~~~~~~~~~~~~~~ | The script 'needs-v8.ps1' cannot be run because it contained a | "#requires" statement for PowerShell 8.0. The version of PowerShell that | is required by the script does not match the currently running version | of PowerShell 7.6.9.#Requires -Modules, shown later, and#Requires -RunAsAdministratorwork the same way. It's much better to fail on line 1 than halfway through a change.
Execution policy: a Windows reminder
On Windows, the execution policy controls whether scripts can run at all. It's a safety belt against accidentally running a downloaded script, not a security boundary, and it doesn't exist on Linux and macOS:
Get-ExecutionPolicy
Get-ExecutionPolicy -ListOn Linux, PowerShell 7.6.9:
Unrestricted
Scope ExecutionPolicy
----- ---------------
MachinePolicy Unrestricted
UserPolicy Unrestricted
Process Unrestricted
CurrentUser Unrestricted
LocalMachine UnrestrictedOn my Windows 11 machine, Windows PowerShell 5.1:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Bypass
CurrentUser RemoteSigned
LocalMachine UndefinedThe scope that wins is the first one in the list that isn't Undefined. Process shows
Bypass here only because the shell I ran it from was started with -ExecutionPolicy Bypass.
The setting that matters is CurrentUser = RemoteSigned: local scripts run, while
downloaded scripts must be signed or unblocked. On a fresh Windows client where everything
is Undefined, the effective policy is Restricted and no script runs at all. I started a
5.1 process with -ExecutionPolicy Restricted, which affects only that process, and ran a
script in it. It failed with
…\Deploy-App.ps1 cannot be loaded because running scripts is disabled on this system and
the error ID UnauthorizedAccess.
The usual fix for your own account is below. It changes the machine's configuration, so I didn't run it for this article:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Unblock-File -Path .\Downloaded-Tool.ps1Unblock-File removes the "downloaded from the internet" mark from a file you've reviewed.
In scheduled tasks, prefer powershell.exe -ExecutionPolicy Bypass -File … (or the pwsh
equivalent) on the command line. It applies to that one process and leaves machine policy
alone.
Scopes: who can see which variable
Every script, function and script block runs in its own scope. The rules fit in three lines:
- Code can read variables from its own scope and from any parent scope.
- Assigning to a variable creates or changes it in the current scope, even if a parent has a variable with the same name.
- A scope modifier (
$script:,$global:,$private:,$local:) overrides rule 2.
Rule 2 is the one that surprises people:
$counter = 0
$environment = 'staging'
function Add-Count {
$counter++
"inside Add-Count: counter = $counter, environment = $environment"
}
Add-Count
Add-Count
"outside: counter = $counter"
function Add-ScriptCount {
$script:counter++
}
Add-ScriptCount
Add-ScriptCount
"after two Add-ScriptCount calls: counter = $counter"inside Add-Count: counter = 1, environment = staging
inside Add-Count: counter = 1, environment = staging
outside: counter = 0
after two Add-ScriptCount calls: counter = 2Add-Count read $environment from the script scope without trouble. But $counter++
read the script's 0, added one, and stored 1 in a new local $counter that vanished
when the function returned. So it printed 1 every time and never changed the outer value.
$script:counter targets the script-level variable explicitly.
The scopes you'll meet:
| Scope | What it is | When to use it |
|---|---|---|
| Local | The current scope, the default | Almost always |
| Script | The top level of the current .ps1 or .psm1 file | Shared state in a script, or private state in a module |
| Global | The session, outliving any script | Rarely. Only for values the interactive session must keep |
| Private | A modifier: the variable is invisible to child scopes | Keeping a secret or internal value away from called code |
$private: hides a variable even from functions called in the same script:
$private:apiToken = 'tok-7f3a9c'
function Show-Token { "function sees: [$apiToken]" }
Show-Token
"script sees: [$apiToken]"function sees: []
script sees: [tok-7f3a9c]And a script's own variables disappear when it finishes, unless it writes to
$global:. Here set-vars.ps1 contains two assignments:
$deployTarget = 'prod'
$global:lastDeploy = '2026-11-09 21:40'Another script calls it and reads both afterwards:
./set-vars.ps1
"deployTarget: [$deployTarget]"
"lastDeploy: [$lastDeploy]"deployTarget: []
lastDeploy: [2026-11-09 21:40]My advice: pass values in through parameters and out through output, and use $script:
for state shared inside one file. Every use of $global: is a variable that some other
script can accidentally overwrite.
Dot-sourcing
Running a script with ./helpers.ps1 gives it its own scope, so the functions and
variables it defines vanish when it returns. Dot-sourcing, a dot and a space in front
of the path, runs it in the caller's scope instead, so everything it defines stays
behind. Given this helpers.ps1:
$logLevel = 'DEBUG'
function Write-Log {
param([string]$Message)
'{0} [{1}] {2}' -f (Get-Date -Format 'HH:mm:ss'), $logLevel, $Message
}compare the two ways of loading it:
$logLevel = 'INFO'
./helpers.ps1
"after running: Write-Log defined: $([bool](Get-Command -Name Write-Log -ErrorAction Ignore)); logLevel = $logLevel"
. ./helpers.ps1
"after dot-sourcing: Write-Log defined: $([bool](Get-Command -Name Write-Log -ErrorAction Ignore)); logLevel = $logLevel"
Write-Log -Message 'deploy started'after running: Write-Log defined: False; logLevel = INFO
after dot-sourcing: Write-Log defined: True; logLevel = DEBUG
21:58:00 [DEBUG] deploy startedDot-sourcing gave us Write-Log, and it also overwrote our $logLevel with the
helper's DEBUG. That's the cost. A dot-sourced file can silently clobber any variable in
your script, and you can't see it happen by reading the calling code.
Dot-sourcing is fine for small, single-purpose files of function definitions. Inside a
script, write . $PSScriptRoot/helpers.ps1 so it works from any working directory. Once
helpers are shared between scripts, or carry state like $logLevel, they belong in a
module, which gives you the functions without the leaked variables.
Building a script module (.psm1)
A script module is a .psm1 file of functions. Importing it gives you the functions it
exports, and nothing else. Variables and helper functions stay private to the module. This
LogTools.psm1 has two public functions, one private helper, and a module-level variable:
# Module-level state: shared by the functions in this module, invisible outside it.
$script:LinePattern = '^(?<time>\S+) (?<level>INFO|WARN|ERROR|FATAL) (?<service>\S+) (?<message>.*)$'
function ConvertFrom-LogLine {
param([string]$Line)
if ($Line -match $script:LinePattern) {
[pscustomobject]@{
Time = $Matches.time
Level = $Matches.level
Service = $Matches.service
Message = $Matches.message
}
}
}
function Get-LogEntry {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]$Path,
[ValidateSet('INFO', 'WARN', 'ERROR', 'FATAL')]
[string[]]$Level
)
process {
foreach ($line in Get-Content -LiteralPath $Path) {
$entry = ConvertFrom-LogLine -Line $line
if ($entry -and (-not $Level -or $entry.Level -in $Level)) {
$entry
}
}
}
}
function Get-LogSummary {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('FullName')]
[string]$Path
)
process {
$entries = @(Get-LogEntry -Path $Path)
[pscustomobject]@{
Log = Split-Path -Path $Path -Leaf
Lines = $entries.Count
Errors = @($entries | Where-Object Level -in 'ERROR', 'FATAL').Count
}
}
}
Export-ModuleMember -Function Get-LogEntry, Get-LogSummaryImport it by path and use it:
Import-Module -Name ./LogTools/LogTools.psm1
Get-Command -Module LogTools | Format-Table -Property CommandType, Name, Version
Get-LogSummary -Path ./logs/billing.log | Format-Table
Get-LogEntry -Path ./logs/billing.log -Level FATAL | Format-ListCommandType Name Version
----------- ---- -------
Function Get-LogEntry 0.0
Function Get-LogSummary 0.0
Log Lines Errors
--- ----- ------
billing.log 3 2
Time : 2026-11-09T09:02:41Z
Level : FATAL
Service : billing
Message : ledger write failed: disk quota exceededThe private parts really are private:
Import-Module -Name ./LogTools/LogTools.psm1
ConvertFrom-LogLine -Line 'test'
"LinePattern outside the module: [$LinePattern]"ConvertFrom-LogLine: /home/sid/modules/m2-private.ps1:3
Line |
3 | ConvertFrom-LogLine -Line 'test'
| ~~~~~~~~~~~~~~~~~~~
| The term 'ConvertFrom-LogLine' is not recognized as a name of a cmdlet,
| function, script file, or executable program. Check the spelling of the
| name, or if a path was included, verify that the path is correct and try
| again.
LinePattern outside the module: []Inside a module, $script: means "module scope". It's the right place for configuration
and caches that every function in the module shares. The version shows 0.0 because a bare
.psm1 has no metadata. That's what the manifest is for.
Module manifests
A manifest (.psd1) describes the module: its version, its author, what it exports, and
which PowerShell version it needs. New-ModuleManifest writes one. The @manifest below is
splatting, passing a hashtable's keys as parameter names, which keeps long commands readable:
$manifest = @{
Path = './LogTools/LogTools.psd1'
RootModule = 'LogTools.psm1'
ModuleVersion = '1.0.0'
Author = 'Platform Team'
Description = 'Parse and summarise application log files.'
PowerShellVersion = '7.2'
FunctionsToExport = @('Get-LogEntry', 'Get-LogSummary')
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
}
New-ModuleManifest @manifest
$module = Test-ModuleManifest -Path ./LogTools/LogTools.psd1
"$($module.Name) $($module.Version) exports: $($module.ExportedFunctions.Keys -join ', ')"LogTools 1.0.0 exports: Get-LogEntry, Get-LogSummaryThe generated file is about 130 lines, mostly comments. These are the lines that matter:
Get-Content -Path ./LogTools/LogTools.psd1 |
Select-String -Pattern '^\s*(RootModule|ModuleVersion|GUID|Author|PowerShellVersion|FunctionsToExport|CmdletsToExport) ' |
ForEach-Object { $_.Line.Trim() }RootModule = 'LogTools.psm1'
ModuleVersion = '1.0.0'
GUID = '097315d4-7d42-4813-8094-405fa9843759'
Author = 'Platform Team'
PowerShellVersion = '7.2'
FunctionsToExport = 'Get-LogEntry', 'Get-LogSummary'
CmdletsToExport = @()Some guidance on the fields:
RootModuleis the.psm1(or.dll) to load. Without it, importing the manifest loads no code at all.ModuleVersionis whatGet-Module,#Requiresand the Gallery use. Bump it on every release.FunctionsToExport: list names explicitly.'*'works, but then PowerShell has to load the module to discover what's in it, which slows autoloading. And the manifest overridesExport-ModuleMember: a function missing from this list stays hidden even if the.psm1exports it. That's a common mistake, shown below.GUIDis generated for you. Keep it stable across versions.PowerShellVersion, and optionallyCompatiblePSEditions = 'Core', make imports fail clearly on hosts that are too old.
PSModulePath and autoloading
You never typed Import-Module for Get-ChildItem. PowerShell autoloads a module the
first time you call one of its commands, as long as the module sits in a folder listed in
$env:PSModulePath:
$env:PSModulePath -split [System.IO.Path]::PathSeparatorOn Linux with PowerShell 7.6.9:
/home/sid/.local/share/powershell/Modules
/usr/local/share/powershell/Modules
/home/sid/.local/opt/powershell/7.6.9/ModulesThese are the current user's modules, all users' modules, and the modules that ship inside
the PowerShell installation (this one was unpacked per user, as in
Installing PowerShell 7; a package install uses
/opt/microsoft/powershell/7/Modules). On Windows the folders differ by edition, and they
are not shared:
| Windows PowerShell 5.1 | PowerShell 7 on Windows | |
|---|---|---|
| Current user | Documents\WindowsPowerShell\Modules | Documents\PowerShell\Modules |
| All users | C:\Program Files\WindowsPowerShell\Modules | C:\Program Files\PowerShell\Modules |
| Built in | C:\Windows\System32\WindowsPowerShell\v1.0\Modules | $PSHOME\Modules |
PowerShell 7 on Windows also appends the 5.1 folders to its path, so it can load many
Windows PowerShell modules. 5.1 does not see modules installed for 7. On my test
machine, the 5.1 user path pointed into OneDrive\Documents\WindowsPowerShell\Modules,
because OneDrive had redirected the Documents folder. If modules installed "for the current
user" seem to vanish on a OneDrive-synced PC, that's the place to look.
Autoloading needs a specific layout: <a folder on PSModulePath>/<ModuleName>/<version>/,
with the manifest named after the module. Here I copy LogTools into that layout under a
local modules folder and add the folder to the path for this session only:
New-Item -ItemType Directory -Path ./modules/LogTools/1.0.0 -Force | Out-Null
Copy-Item -Path ./LogTools/LogTools.psd1, ./LogTools/LogTools.psm1 -Destination ./modules/LogTools/1.0.0/
$env:PSModulePath = "$PWD/modules" + [System.IO.Path]::PathSeparator + $env:PSModulePath
"Loaded before: $(@(Get-Module -Name LogTools).Count)"
Get-Module -Name LogTools -ListAvailable | Format-List -Property Name, Version, ModuleBase
Get-LogSummary -Path ./logs/api.log | Format-Table
"Loaded after: $((Get-Module -Name LogTools).Version)"Loaded before: 0
Name : LogTools
Version : 1.0.0
ModuleBase : /home/sid/modules/modules/LogTools/1.0.0
Log Lines Errors
--- ----- ------
api.log 4 1
Loaded after: 1.0.0No Import-Module anywhere: calling Get-LogSummary found the module through the path and
imported it. To make that permanent for yourself, put the module in your user module folder
from the table, or add your folder to PSModulePath in your profile. In scripts, an
explicit Import-Module LogTools at the top is still good practice. It documents the
dependency and fails early with a clear message.
Import-Module -Force during development
Importing a module that is already loaded does nothing. PowerShell sees the name and returns. While you're editing a module, that means your changes are silently ignored:
Import-Module -Name ./LogTools/LogTools.psd1
Get-LogSummary -Path ./logs/api.log | Format-Table
# Simulate saving an edited LogTools.psm1 in your editor:
Copy-Item -Path ./LogTools.v2.psm1 -Destination ./LogTools/LogTools.psm1
Import-Module -Name ./LogTools/LogTools.psd1
Get-LogSummary -Path ./logs/api.log | Format-Table
Import-Module -Name ./LogTools/LogTools.psd1 -Force
Get-LogSummary -Path ./logs/api.log | Format-TableLog Lines Errors
--- ----- ------
api.log 4 1
Log Lines Errors
--- ----- ------
api.log 4 1
Log Lines Warnings Errors
--- ----- -------- ------
api.log 4 1 1The edited version adds a Warnings column, and only appeared after -Force, which
removes the loaded module and imports it again. Make Import-Module … -Force the first line
of your test loop. If something still looks stale (PowerShell classes defined in a module
are the classic case), start a fresh pwsh session.
The PowerShell Gallery
The PowerShell Gallery (powershellgallery.com) is the public repository of modules.
PowerShell 7.4 and later ship PSResourceGet (Find-PSResource, Install-PSResource,
Update-PSResource, Save-PSResource), the successor to the older PowerShellGet
commands (Find-Module, Install-Module). Here I install Microsoft's SecretManagement
module for the current user only. No admin or sudo is needed:
Find-PSResource -Name Microsoft.PowerShell.SecretManagement -Repository PSGallery
Install-PSResource -Name Microsoft.PowerShell.SecretManagement -Scope CurrentUser -Repository PSGallery -TrustRepository
Get-InstalledPSResource -Name Microsoft.PowerShell.SecretManagement | Format-List -Property Name, Version, InstalledLocationName Version Prerelease Repository Description
---- ------- ---------- ---------- -----------
Microsoft.PowerShell.SecretManagement 1.1.2 PSGallery …
Name : Microsoft.PowerShell.SecretManagement
Version : 1.1.2
InstalledLocation : /home/sid/.local/share/powershell/Modules-TrustRepository skips the "untrusted repository" confirmation for this one command. The
Gallery is untrusted by default, because anyone can publish to it. Review what you install,
just as you would an npm or PyPI package.
When I tried to Import-Module the new module in the same script that installed it, the
import failed with no valid module file was found in any module directory. In a new
pwsh session it loaded normally:
Import-Module -Name Microsoft.PowerShell.SecretManagement
Get-Command -Module Microsoft.PowerShell.SecretManagement | Format-Table -Property CommandType, Name, VersionCommandType Name Version
----------- ---- -------
Cmdlet Get-Secret 1.1.2
Cmdlet Get-SecretInfo 1.1.2
Cmdlet Get-SecretVault 1.1.2
Cmdlet Register-SecretVault 1.1.2
Cmdlet Remove-Secret 1.1.2
Cmdlet Set-Secret 1.1.2
Cmdlet Set-SecretInfo 1.1.2
Cmdlet Set-SecretVaultDefault 1.1.2
Cmdlet Test-SecretVault 1.1.2
Cmdlet Unlock-SecretVault 1.1.2
Cmdlet Unregister-SecretVault 1.1.2So install in one step and use the module in the next, which is how a CI job or a server
build script is usually laid out anyway. I removed it afterwards with
Uninstall-PSResource -Name Microsoft.PowerShell.SecretManagement -Scope CurrentUser.
For build servers and air-gapped machines, Save-PSResource downloads a module into a
folder of your choice without installing it. That lets you commit or cache a known version.
The destination folder must already exist:
Save-PSResource -Name Microsoft.PowerShell.SecretManagement -Version 1.1.2 -Path ./vendor -Repository PSGallery -TrustRepositorySave-PSResource: /home/sid/modules/gallery-save-err.ps1:1
Line |
1 | … oft.PowerShell.SecretManagement -Version 1.1.2 -Path ./vendor -Reposi …
| ~~~~~~~~
| Cannot bind parameter 'Path' to the target. Exception setting "Path":
| "Cannot find path '/home/sid/modules/vendor'
| because it does not exist."New-Item -ItemType Directory -Path ./vendor -Force | Out-Null
Save-PSResource -Name Microsoft.PowerShell.SecretManagement -Version 1.1.2 -Path ./vendor -Repository PSGallery -TrustRepository
(Get-ChildItem -Path ./vendor -Recurse -Depth 1).FullName.Replace("$PWD/", '')vendor/Microsoft.PowerShell.SecretManagement
vendor/Microsoft.PowerShell.SecretManagement/1.1.2The saved folder already has the <Name>/<version>/ layout, so adding ./vendor to
PSModulePath makes it autoload.
The older commands still work in 7.6. Install-Module asks before using an untrusted
repository. With nobody there to answer, it declined:
Find-Module -Name Microsoft.PowerShell.SecretManagement | Format-Table -Property Version, Name, Repository
Install-Module -Name Microsoft.PowerShell.SecretManagement -Scope CurrentUserVersion Name Repository
------- ---- ----------
1.1.2 Microsoft.PowerShell.SecretManagement PSGallery
Untrusted repository
You are installing the modules from an untrusted repository. If you trust this
repository, change its InstallationPolicy value by running the Set-PSRepository
cmdlet. Are you sure you want to install the modules from 'PSGallery'?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "N"):WARNING: User declined to install module (Microsoft.PowerShell.SecretManagement).Windows PowerShell 5.1 is the awkward one. My Windows 11 machine still had the versions that originally shipped with Windows:
Get-Module -ListAvailable -Name PowerShellGet, PackageManagement, Microsoft.PowerShell.PSResourceGet |
Select-Object -Property Name, Version | Format-Table -AutoSizeName Version
---- -------
PackageManagement 1.0.0.1
PowerShellGet 1.0.0.1PowerShellGet 1.0.0.1 is old enough that installing from the Gallery commonly starts with a prompt to bootstrap the NuGet provider. Updating PowerShellGet first, or installing PSResourceGet into 5.1, makes life easier. I didn't install anything into the host's 5.1 for this article.
Versioning and side-by-side installs
Because modules live in <Name>/<version>/ folders, several versions can be installed side
by side. PowerShell imports the highest version unless told otherwise. A release workflow
looks like this: bump the version in your source folder (here the new version also exports
a new function), then publish a copy into a new version folder:
$env:PSModulePath = "$PWD/modules" + [System.IO.Path]::PathSeparator + $env:PSModulePath
# Bump the version in the source folder, then publish it to a versioned folder.
Update-ModuleManifest -Path ./LogTools/LogTools.psd1 -ModuleVersion 1.1.0 `
-FunctionsToExport Get-LogEntry, Get-LogSummary, Get-LogLevelCount
New-Item -ItemType Directory -Path ./modules/LogTools/1.1.0 -Force | Out-Null
Copy-Item -Path ./LogTools/LogTools.psd1, ./LogTools/LogTools.psm1 -Destination ./modules/LogTools/1.1.0/
Get-Module -Name LogTools -ListAvailable | Format-Table -Property Name, Version
Import-Module -Name LogTools
"Imported by default: $((Get-Module -Name LogTools).Version)"
Remove-Module -Name LogTools
Import-Module -Name LogTools -RequiredVersion 1.0.0
"Imported with -RequiredVersion: $((Get-Module -Name LogTools).Version)"Name Version
---- -------
LogTools 1.1.0
LogTools 1.0.0
Imported by default: 1.1.0
Imported with -RequiredVersion: 1.0.0The order matters. My first attempt copied the 1.0.0 files into the 1.1.0 folder and then
tried to bump the version there:
New-Item -ItemType Directory -Path ./modules/LogTools/1.1.0 -Force | Out-Null
Copy-Item -Path ./modules/LogTools/1.0.0/* -Destination ./modules/LogTools/1.1.0/
Update-ModuleManifest -Path ./modules/LogTools/1.1.0/LogTools.psd1 -ModuleVersion 1.1.0Update-ModuleManifest: /home/sid/modules/m7a-version-wrong.ps1:3
Line |
3 | Update-ModuleManifest -Path ./modules/LogTools/1.1.0/LogTools.psd1 -M …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot update the manifest properly. 'The ModuleVersion key in module
| manifest
| '/home/sid/modules/modules/LogTools/1.1.0/LogTools.psd1' specifies module version '1.0.0' which does not match its version folder name at '/home/sid/modules/modules/LogTools/1.1.0'. Change the value of the ModuleVersion key to match the version folder name.'PowerShell checks that a manifest inside a version folder matches the folder name, and it refuses to edit one that doesn't. Do version bumps in your source tree.
Scripts state the minimum version they need with #Requires, which refuses to start if
it isn't available:
#Requires -Modules @{ ModuleName = 'LogTools'; ModuleVersion = '2.0.0' }
Get-LogSummary -Path ./logs/api.log./needs-logtools2.ps1: /home/sid/modules/m8-requires-module.ps1:2
Line |
2 | ./needs-logtools2.ps1
| ~~~~~~~~~~~~~~~~~~~~~
| The script 'needs-logtools2.ps1' cannot be run because the following
| modules that are specified by the "#requires" statements of the script
| are missing: The module 'LogTools' cannot be found with ModuleVersion
| '2.0.0'..ModuleVersion in #Requires means "this version or newer". Use RequiredVersion in the
hashtable to pin an exact version. Follow semantic versioning: bump the patch number for
fixes, the minor number when you add functions (as Get-LogLevelCount did here), and the
major number when you remove or rename something that callers use.
Where you'll use this
- A team toolbox module. One
OpsToolsmodule in a Git repository, published to an internal feed or a file share, imported by every scheduled job. Fix a bug once, bump the version, and every job picks it up. - Scheduled scripts.
pwsh -NoProfile -NonInteractive -Filewith$PSScriptRootfor config files and#Requiresfor dependencies. Scripts started from cron, Task Scheduler, Jenkins or GitHub Actions get a working directory you don't control. - Pinning dependencies in CI.
Save-PSResourceinto avendorfolder orInstall-PSResource -Versionwith an exact number, so a Gallery release can't break your pipeline overnight. - Profiles. Your
$PROFILEcanImport-Moduleyour toolbox, rather than dot-sourcing a pile of loose files.
Real modules quickly outgrow a single .psm1. The common layout keeps one function per
file, in Public and Private folders, and a tiny loader:
OpsTools
OpsTools/OpsTools.psd1
OpsTools/OpsTools.psm1
OpsTools/Private
OpsTools/Private/ConvertFrom-LogLine.ps1
OpsTools/Public
OpsTools/Public/Get-ErrorReport.ps1
OpsTools/Public/Get-LogEntry.ps1OpsTools.psm1 dot-sources every file and exports only the public ones. Here dot-sourcing
is exactly right, because the module is the scope being populated:
$public = @(Get-ChildItem -Path "$PSScriptRoot/Public/*.ps1")
$private = @(Get-ChildItem -Path "$PSScriptRoot/Private/*.ps1")
foreach ($file in $private + $public) {
. $file.FullName
}
Export-ModuleMember -Function $public.BaseNamePublic/Get-ErrorReport.ps1 builds on Get-LogEntry:
function Get-ErrorReport {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$LogPath)
Get-ChildItem -Path $LogPath -Filter *.log |
Get-LogEntry |
Where-Object Level -in 'ERROR', 'FATAL' |
Group-Object -Property Service |
Sort-Object -Property Count -Descending |
Select-Object -Property @{ Name = 'Service'; Expression = { $_.Name } }, Count
}Generate the manifest, import, and use it:
New-ModuleManifest -Path ./OpsTools/OpsTools.psd1 -RootModule OpsTools.psm1 `
-ModuleVersion 0.3.0 -FunctionsToExport Get-LogEntry, Get-ErrorReport
Import-Module -Name ./OpsTools/OpsTools.psd1
Get-Command -Module OpsTools | Format-Table -Property CommandType, Name, Version
Get-ErrorReport -LogPath ./logsCommandType Name Version
----------- ---- -------
Function Get-ErrorReport 0.3.0
Function Get-LogEntry 0.3.0
Service Count
------- -----
billing 2
api 1Adding a function means adding a file to Public and its name to FunctionsToExport.
Code review diffs stay small, and two people rarely edit the same file.
Common mistakes
A new function is missing after import
You added Get-LogLevelCount to the .psm1 and to its Export-ModuleMember line, and
re-imported with -Force, but the manifest's FunctionsToExport still lists only the old
two:
Import-Module -Name ./LogTools/LogTools.psd1 -Force
Get-LogLevelCount -Path ./logs/api.logGet-LogLevelCount: /home/sid/modules/m6b-export-mismatch.ps1:2
Line |
2 | Get-LogLevelCount -Path ./logs/api.log
| ~~~~~~~~~~~~~~~~~~~
| The term 'Get-LogLevelCount' is not recognized as a name of a cmdlet,
| function, script file, or executable program. Check the spelling of the
| name, or if a path was included, verify that the path is correct and try
| again.When you import a manifest, its export lists win. Add the name to FunctionsToExport
(Update-ModuleManifest -FunctionsToExport …), as the versioning example did.
Unapproved verbs
A module with a function named Fetch-LogFile imports, but it complains on every import:
New-Item -ItemType Directory -Path ./BadVerbs -Force | Out-Null
@'
function Fetch-LogFile { 'fetched' }
function Get-LogFile { 'got' }
'@ | Set-Content -Path ./BadVerbs/BadVerbs.psm1
Import-Module -Name ./BadVerbs/BadVerbs.psm1
Get-Command -Module BadVerbs | Format-Table -Property Name, VerbWARNING: The names of some imported commands from the module 'BadVerbs' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
Name Verb
---- ----
Fetch-LogFile Fetch
Get-LogFile GetRename to an approved verb (Get-, Receive-, Copy-). Check with Get-Verb.
-DisableNameChecking hides the warning, but it only moves the problem to your users.
Expecting a script to leave its functions behind
./helpers.ps1 defines functions in the script's own scope, and they disappear when it
returns ("Write-Log defined: False" above). Dot-source it (. ./helpers.ps1), or better,
turn it into a module.
Editing a loaded module and seeing no change
Shown above: Import-Module without -Force is a no-op for a module that is already
loaded. Use -Force during development, or a fresh session.
Summary
- A script can have
[CmdletBinding()]andparam()just like a function. Run it with a path (./script.ps1), or withpwsh -NoProfile -NonInteractive -Filefrom schedulers. $PSScriptRootis the script's own folder. Build paths to config and helper files from it, never from the current directory.#Requireschecks versions and modules before line 1 runs.- Assigning to a variable creates it in the current scope. Reading falls back to parent
scopes. Use
$script:for shared state in a file.$global:is rarely the right answer. - Dot-sourcing (
. ./file.ps1) runs a file in the caller's scope. It keeps the functions, but also any variables it sets, which can overwrite yours. - A module (
.psm1plus a.psd1manifest) exports only what you list, keeps its helpers and$script:variables private, and carries a version.FunctionsToExportin the manifest overridesExport-ModuleMember. - Modules in
<PSModulePath folder>/<Name>/<Version>/autoload. Several versions can sit side by side, and-RequiredVersionor#Requires -Modules @{…}picks one. Import-Module -Forcereloads a module you're editing. Without it, re-importing does nothing.Install-PSResource -Scope CurrentUser(7.4+) installs from the Gallery without admin rights.Save-PSResourcevendors a pinned copy. Windows PowerShell 5.1 ships an old PowerShellGet that should be updated first.
Exercises
Create tools/settings.psd1 containing a hashtable with Environment, ApiUrl and
TimeoutSec. Write tools/Get-Setting.ps1 with a mandatory -Name parameter that prints
that setting's value, and throws a helpful error for unknown names. Prove it works when
called from the project folder and from a sibling folder other/.
Show Solution
tools/settings.psd1:
@{
Environment = 'staging'
ApiUrl = 'https://api.staging.example.com'
TimeoutSec = 30
}tools/Get-Setting.ps1:
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Name
)
$settings = Import-PowerShellDataFile -Path (Join-Path -Path $PSScriptRoot -ChildPath 'settings.psd1')
if (-not $settings.ContainsKey($Name)) {
throw "Unknown setting '$Name'. Known settings: $($settings.Keys -join ', ')"
}
$settings[$Name]Test:
./tools/Get-Setting.ps1 -Name ApiUrl
Set-Location -Path ./other
../tools/Get-Setting.ps1 -Name TimeoutSechttps://api.staging.example.com
30Because the path is built from $PSScriptRoot, the working directory doesn't matter.
Without running it, write down the three lines this script prints. Then run it and check.
$retries = 3
function Set-Retries {
$retries = 10
"inside Set-Retries: $retries"
}
function Set-RetriesScript {
$script:retries = 5
}
Set-Retries
"after Set-Retries: $retries"
Set-RetriesScript
"after Set-RetriesScript: $retries"Show Solution
inside Set-Retries: 10
after Set-Retries: 3
after Set-RetriesScript: 5Set-Retries assigned to $retries, which created a local variable that only lived inside
the function. The script's $retries was still 3. Set-RetriesScript used the $script:
modifier, so it changed the script-level variable.
Turn the Write-Log helper into a module called OpsLog, in an OpsLog folder. Keep the
log level in a module-scoped variable that callers can't see, export only Write-Log, and
give the module a manifest with version 0.1.0. Import it, write a log line, and show that
the log-level variable didn't leak into your script.
Show Solution
New-Item -ItemType Directory -Path ./OpsLog -Force | Out-Null
@'
$script:LogLevel = 'INFO'
function Write-Log {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Message)
'{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $script:LogLevel, $Message
}
Export-ModuleMember -Function Write-Log
'@ | Set-Content -Path ./OpsLog/OpsLog.psm1
New-ModuleManifest -Path ./OpsLog/OpsLog.psd1 -RootModule OpsLog.psm1 `
-ModuleVersion 0.1.0 -FunctionsToExport Write-Log
Import-Module -Name ./OpsLog/OpsLog.psd1
Write-Log -Message 'backup started'
"LogLevel visible outside the module: [$LogLevel]"
(Get-Module -Name OpsLog).Version.ToString()2026-11-09 22:02:12 [INFO] backup started
LogLevel visible outside the module: []
0.1.0Unlike the dot-sourced helper, importing the module didn't touch any of the caller's variables.
Publish OpsLog 0.1.0 into ./modules/OpsLog/0.1.0. Then add a Write-LogError function,
bump the version to 0.2.0 in the source folder, and publish that to
./modules/OpsLog/0.2.0. With ./modules on PSModulePath, show that both versions are
available, that a script with #Requires -Modules @{ ModuleName = 'OpsLog'; ModuleVersion = '0.2.0' } runs with 0.2.0, and that importing -RequiredVersion 0.1.0 gives you only
Write-Log.
Show Solution
$env:PSModulePath = "$PWD/modules" + [System.IO.Path]::PathSeparator + $env:PSModulePath
New-Item -ItemType Directory -Path ./modules/OpsLog/0.1.0 -Force | Out-Null
Copy-Item -Path ./OpsLog/OpsLog.psd1, ./OpsLog/OpsLog.psm1 -Destination ./modules/OpsLog/0.1.0/
Add-Content -Path ./OpsLog/OpsLog.psm1 -Value @'
function Write-LogError {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Message)
Write-Log -Message "ERROR $Message"
}
Export-ModuleMember -Function Write-Log, Write-LogError
'@
Update-ModuleManifest -Path ./OpsLog/OpsLog.psd1 -ModuleVersion 0.2.0 -FunctionsToExport Write-Log, Write-LogError
New-Item -ItemType Directory -Path ./modules/OpsLog/0.2.0 -Force | Out-Null
Copy-Item -Path ./OpsLog/OpsLog.psd1, ./OpsLog/OpsLog.psm1 -Destination ./modules/OpsLog/0.2.0/
Get-Module -Name OpsLog -ListAvailable | Format-Table -Property Name, Version
@'
#Requires -Modules @{ ModuleName = 'OpsLog'; ModuleVersion = '0.2.0' }
Write-LogError -Message 'disk full on db01'
"OpsLog version in use: $((Get-Module -Name OpsLog).Version)"
'@ | Set-Content -Path ./needs-oplog.ps1
./needs-oplog.ps1Name Version
---- -------
OpsLog 0.2.0
OpsLog 0.1.0
2026-11-09 22:02:14 [INFO] ERROR disk full on db01
OpsLog version in use: 0.2.0In a new session:
$env:PSModulePath = "$PWD/modules" + [System.IO.Path]::PathSeparator + $env:PSModulePath
Import-Module -Name OpsLog -RequiredVersion 0.1.0
(Get-Command -Module OpsLog).NameWrite-Log#Requires imported the module for the script and enforced the minimum version. Pinning
0.1.0 gives you exactly that release, without the function added in 0.2.0.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 on
Windows 11, November 2026. All Linux examples were run as shown with
pwsh -NoProfile -File, including a real install of Microsoft.PowerShell.SecretManagement
1.1.2 from the PowerShell Gallery, which I uninstalled afterwards. On Windows I only ran
read-only commands (Get-ExecutionPolicy -List, Get-Module -ListAvailable,
$env:PSModulePath) plus one script inside a process started with
-ExecutionPolicy Restricted. Set-ExecutionPolicy and Unblock-File were not run,
because they change machine settings. Paths from the test machine's scratch directories are shown shortened to /home/sid/….
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.