# How to Write a PowerShell Script with Safe Dry Runs

> Canonical: https://skillalmanac.com/learn/write-a-powershell-script-with-an-ai-agent | Updated: 2026-11-25 | Index status: index-eligible

Write an advanced PowerShell script, add ShouldProcess and -WhatIf, test its observable result, and diagnose execution-policy failures without weakening policy blindly.

## Facts

- Checked 2026-11-25: On Windows, Group Policy scopes override ordinary scopes; without Group Policy, precedence is Process, CurrentUser, then LocalMachine. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies
- Checked 2026-11-25: Execution policy is defense in depth, not a security boundary. A process-scoped policy lasts only for that session and its child sessions. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies
- Checked 2026-11-25: Under RemoteSigned, downloaded unsigned scripts are blocked unless signed or unblocked; locally written scripts do not require a signature. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies
- Checked 2026-11-25: SupportsShouldProcess adds WhatIf and Confirm, but state-changing code must call ShouldProcess for those controls to govern the action. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute
- Checked 2026-11-25: PowerShell guidance recommends approved Verb-SingularNoun function names; Get-Verb lists approved verbs. https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions

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

1. On Windows, run `Get-ExecutionPolicy` for the effective policy and `Get-ExecutionPolicy -List` to inspect all scopes.
2. `MachinePolicy` and `UserPolicy` come 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.
3. Without Group Policy, `Process` has precedence over `CurrentUser`, which has precedence over `LocalMachine`. A process-scoped value disappears when that PowerShell session and its child sessions close.
4. 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 `RemoteSigned` as allowing local unsigned scripts while requiring downloaded scripts to be signed unless they are unblocked.
5. Changing `LocalMachine` requires an elevated PowerShell session. A `CurrentUser` change persists for that user, while a `Process` change 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:

```powershell
[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

1. In a disposable test folder, choose a nonexistent path and run `./New-ExampleFile.ps1 -Path ./example.txt -WhatIf` (use `.\New-ExampleFile.ps1` and `.\example.txt` in Windows PowerShell).
2. Confirm that PowerShell reports the proposed create action and that `Test-Path ./example.txt` returns `False`. If the file appears, a change occurred despite the dry run; stop and inspect every state-changing path.
3. Review the script for commands outside `ShouldProcess`, including native programs and direct .NET calls. `-WhatIf` does not automatically intercept them.
4. Only after the target and action are correct should you run without `-WhatIf`. `-Confirm` requests confirmation when `ShouldProcess` and 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 -ExecutionPolicy` ends with its window. If the script works in one window and fails in another, compare `Get-ExecutionPolicy -List` in 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 run `Unblock-File` on it. Some download tools, including `curl.exe` and `Invoke-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 `CmdletBinding` and rerun.
- **-WhatIf misses custom deletes.** Native executables and direct `.NET` calls 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](/skills/skill-almanac/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

- [coding-agent-guardrails](https://skillalmanac.com/skills/skill-almanac/coding-agent-guardrails.md): Platform Score 60/100

## Related guides

- [How to Write a Regex with an AI Agent, Test Cases First](https://skillalmanac.com/learn/write-a-regex-with-an-ai-agent.md)
- [Write a Bash Script with an AI Agent: Prompt, Lint, Run](https://skillalmanac.com/learn/write-a-bash-script-with-an-ai-agent.md)
- [How to Use an AI Agent on a First Task You Can Check](https://skillalmanac.com/learn/how-to-use-an-ai-agent.md)
- [Check a Resume for ATS Problems With an AI Agent](https://skillalmanac.com/learn/check-a-resume-for-ats-with-an-ai-agent.md)
- [How to write a bug report a developer can reproduce](https://skillalmanac.com/learn/write-a-bug-report-with-ai.md)

## Sources

- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies
- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute
- https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions

Platform Scores report our assessment under a published method. They are not a safety guarantee.
