Learn › PowerShell

PowerShell Modules and Safe Automation: SupportsShouldProcess, WhatIf and Testing

Package PowerShell functions as a module, add -WhatIf and -Confirm, and test scripts with PSScriptAnalyzer and Pester before production.

Advanced 12 min read
By Gopinath Karthikeyan

Once your team relies on your scripts, quality matters as much as features. This guide covers the habits that separate a handy script from a trustworthy tool: modules, -WhatIf support, and automated checks.

Turn functions into a module

A module is just a folder with a .psm1 file (your functions) and an optional .psd1 manifest (version, author, exported functions).

WinOpsTools\
  WinOpsTools.psd1
  WinOpsTools.psm1
  Public\Get-DiskReport.ps1
  Public\Clear-OldLogs.ps1

WinOpsTools.psm1:

Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" | ForEach-Object { . $_.FullName }
Export-ModuleMember -Function (Get-ChildItem "$PSScriptRoot\Public\*.ps1").BaseName

Create the manifest once:

New-ModuleManifest -Path .\WinOpsTools\WinOpsTools.psd1 -RootModule WinOpsTools.psm1 `
    -ModuleVersion 1.0.0 -Author 'Windows team' -Description 'Admin tools'

Put the folder in a path listed in $env:PSModulePath (or import it directly) and use it:

Import-Module .\WinOpsTools -Force
Get-Command -Module WinOpsTools

Keep the module in Git (see the Git track) so every change is reviewed and versioned.

Add -WhatIf and -Confirm to your own functions

Anything that changes something should support a dry run:

function Clear-OldLogs {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory)] [string] $Path,
        [ValidateRange(1, 3650)] [int] $Days = 30
    )
    $cutoff = (Get-Date).AddDays(-$Days)
    Get-ChildItem -Path $Path -File -Filter *.log |
        Where-Object LastWriteTime -lt $cutoff |
        ForEach-Object {
            if ($PSCmdlet.ShouldProcess($_.FullName, 'Delete')) {
                Remove-Item -LiteralPath $_.FullName
            }
        }
}

Clear-OldLogs -Path D:\Logs\App -Days 30 -WhatIf     # shows what would be deleted
Clear-OldLogs -Path D:\Logs\App -Days 30             # does it

SupportsShouldProcess gives you -WhatIf and -Confirm for free. Users can always preview your tool safely.

Guard rails for destructive scripts

  • Validate inputs ([ValidateSet()], [ValidateRange()], Test-Path) so a typo can’t target C:\.
  • Limit scope: refuse to run against more than N servers without an explicit -Force.
  • Report first, change second: run in report mode, review the output, then run the change.
  • Log every change with who, what and when.
  • Idempotent where possible: running twice should give the same result as once.

Lint with PSScriptAnalyzer

Install-Module PSScriptAnalyzer -Scope CurrentUser
Invoke-ScriptAnalyzer -Path .\WinOpsTools -Recurse

It flags unapproved verbs, plain-text passwords, unused variables, missing ShouldProcess and more.

Test with Pester

Pester is PowerShell’s test framework. A small test file, Get-DiskReport.Tests.ps1:

BeforeAll { . $PSScriptRoot\Public\Get-DiskReport.ps1 }

Describe 'Get-DiskReport' {
    It 'rejects an invalid threshold' {
        { Get-DiskReport -WarnPercent 150 } | Should -Throw
    }
    It 'returns objects with a FreePct property' {
        Mock Get-CimInstance { [pscustomobject]@{ DeviceID = 'C:'; FreeSpace = 5GB; Size = 100GB } }
        (Get-DiskReport -WarnPercent 10).FreePct | Should -Be 5
    }
}
Invoke-Pester -Path .\Tests

Mock replaces real cmdlets during the test, so you test your logic without touching servers.

Put it in a pipeline

Run Invoke-ScriptAnalyzer and Invoke-Pester automatically on every pull request – the Jenkins pipeline guide shows how. Broken tools never reach production.

FAQ

Do admins really need tests? For a one-off command, no. For a tool the whole team runs against production every week, yes – a few tests prevent the outage that costs more than writing them.

What’s next

You’ve completed the PowerShell track. Next, store your tools properly with Git, or learn Linux for Windows admins.

Practise this topic

Test yourself with free questions on this topic – instant answers and explanations.

Start practice questions

PowerShellModulesPesterBest PracticesAdvanced

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn

More in PowerShell