How to Write a PowerShell Script with Safe Dry Runs
Write an advanced PowerShell script, add ShouldProcess and -WhatIf, test its observable result, and diagnose execution-policy failures without weakening policy blindly.
Updated · Markdown version
Start by defining the script's inputs and expected change, then review the generated code before running it. For a script that changes state, add SupportsShouldProcess, guard each change with ShouldProcess, and test with -WhatIf. Execution policy is a separate Windows safety feature: inspect it when a script will not start, but do not weaken an organizational policy merely to run generated code.
Step 1: Check the execution policy
- On Windows, run
Get-ExecutionPolicyfor the effective policy andGet-ExecutionPolicy -Listto inspect all scopes. MachinePolicyandUserPolicycome from Group Policy and override settings made through ordinary PowerShell scopes. If either is configured, follow the administrator's policy rather than trying to bypass it.- Without Group Policy,
Processhas precedence overCurrentUser, which has precedence overLocalMachine. A process-scoped value disappears when that PowerShell session and its child sessions close. - If the policy blocks a script, first verify the script's source and review its contents. For a trusted script, use only an execution-policy change authorized for your environment. Microsoft documents
RemoteSignedas allowing local unsigned scripts while requiring downloaded scripts to be signed unless they are unblocked. - Changing
LocalMachinerequires an elevated PowerShell session. ACurrentUserchange persists for that user, while aProcesschange is temporary.
Check: record both Get-ExecutionPolicy and Get-ExecutionPolicy -List. Do not expect the effective value to equal CurrentUser when Group Policy or Process supplies a higher-precedence setting.
Step 2: Require -WhatIf support in the script
Put this in the agent's instructions: each state-changing path must declare [CmdletBinding(SupportsShouldProcess)] and call $PSCmdlet.ShouldProcess() before the change. The attribute supplies -WhatIf and -Confirm; the call is what makes the guarded action honor them.
For a standalone script, save this shape as New-ExampleFile.ps1 in a test folder:
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[string]$Path
)
if ($PSCmdlet.ShouldProcess($Path, 'Create empty file')) {
New-Item -ItemType File -Path $Path -ErrorAction Stop | Out-Null
}Choose a path that does not already exist. The New verb is on PowerShell's approved list, available through Get-Verb. If you instead write reusable functions, use an approved Verb-SingularNoun name and place them in a script or module with an explicit entry point.
Step 3: Run the dry run
- In a disposable test folder, choose a nonexistent path and run
./New-ExampleFile.ps1 -Path ./example.txt -WhatIf(use.\New-ExampleFile.ps1and.\example.txtin Windows PowerShell). - Confirm that PowerShell reports the proposed create action and that
Test-Path ./example.txtreturnsFalse. If the file appears, a change occurred despite the dry run; stop and inspect every state-changing path. - Review the script for commands outside
ShouldProcess, including native programs and direct .NET calls.-WhatIfdoes not automatically intercept them. - Only after the target and action are correct should you run without
-WhatIf.-Confirmrequests confirmation whenShouldProcessand PowerShell's confirmation rules require it; it is not a substitute for code review.
Check: after the real run, Test-Path ./example.txt should return True. Delete the test artifact only when you have confirmed that exact path is disposable.
Pitfalls
- Process-scope policy disappears. A policy set with
pwsh.exe -ExecutionPolicyends with its window. If the script works in one window and fails in another, compareGet-ExecutionPolicy -Listin each. - Downloaded scripts get blocked. RemoteSigned blocks unsigned scripts that carry the internet mark. Check with
Get-Item -Stream Zone.Identifier, read the script, then runUnblock-Fileon it. Some download tools, includingcurl.exeandInvoke-WebRequest, may not add the mark, so do not rely on the block as a safety check. - -WhatIf reports an unknown parameter. Without the attribute, the agent's script does not accept common parameters. Add
CmdletBindingand rerun. - -WhatIf misses custom deletes. Native executables and direct
.NETcalls do not check ShouldProcess. Ask the agent to wrap each such call in its own ShouldProcess check. - Execution policy is not a security boundary. It prevents accidental runs. It does not stop a determined user from pasting script contents into the console, so it does not replace code review.
When to use a skill instead
A reusable skill can remind an agent to perform the same review, but it is guidance rather than an external enforcement boundary. coding-agent-guardrails is related, yet the supplied catalogue's measured 2026-11-23 evaluation reported NO_LIFT: 12 paired tasks, a pass-rate difference of -5.0 points with a 95% confidence interval from -16.8 to +6.8, and two harmed tasks. Its install probe checked recognition in Claude Code, not safe completion of repository changes. Read the current evidence and keep platform permissions, backups and human review in place.
FAQ
Why does my PowerShell script fail to run on Windows? Execution policy is one possible cause, not the default diagnosis for every failure. Read the complete error, then run Get-ExecutionPolicy and Get-ExecutionPolicy -List if it reports that script execution is disabled or the file is not digitally signed. Do not change a Group Policy setting; use only a policy or unblock action authorized for a script whose source and contents you have verified.
Does -WhatIf stop every change a script makes? No. It only stops changes in code that checks ShouldProcess. Direct native commands and custom .NET calls run unless the script checks the condition itself.
How do I create my own PowerShell script? Create a .ps1 file with an optional [CmdletBinding()] attribute, a param block, validation for required inputs, and the commands to run. A file containing only function definitions merely defines those functions for that script's scope; add an entry point, invoke the function, dot-source the file intentionally, or package reusable commands as a module. Use approved Verb-SingularNoun names for functions and check them with Get-Verb.
Related skills in this catalog
Platform Score is our assessment under a published method. It is not a safety guarantee.
Related guides
Sources
- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies (accessed 2026-11-25)
- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute (accessed 2026-11-25)
- https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions (accessed 2026-11-25)