AI Field Manual
FM-IT-02 · Guide

IT & Systems Administration  ·  Fundamentals

Review an unfamiliar PowerShell script before running it

A colleague forwards cleanup-old-profiles.ps1 and says it ran fine last year. You're asked to run it on a production file server before the weekend. It's 280 lines long and a comment calls it "safe." None of that proves it's safe here, now, or under your account. This guide uses AI as a second reader, not a substitute for a careful review.

Status
Published
Reading time
About 14 minutes
You'll need
The original script as a file, PowerShell 5.1 or 7 for read-only analysis, an approved AI assistant if code may leave the organization, and optionally the PSScriptAnalyzer module
Last reviewed
November 2026
Before you start

Source, trust and scope

The goal is a decision memo: what the script reads, what it writes or deletes, where it sends data, which permissions it needs, and what has to be tested before anyone runs it. The most dangerous question is "does this code look good?" It's too broad. A script can look tidy and still remove the wrong directory, contact an unknown endpoint, or only work because its original author had different credentials.

Write down five facts before you read a line:

  1. Provenance. Who supplied the file? Where's the authoritative repository? Is this the same file that was tested?
  2. Purpose. What business result is expected? "Cleanup" isn't specific enough; name the objects it should change.
  3. Environment. Which Windows and PowerShell versions, modules, domain, server role, paths and privilege level does it assume?
  4. Blast radius. One test user or every profile? One host, or every host it discovers in Active Directory?
  5. Fallback. What can be restored if the script makes partial changes or stops halfway?
Step 1

Freeze the exact artifact

Save a copy in a review folder that isn't the production execution path, and record its hash and signature status. A SHA-256 hash identifies the file's bytes; it doesn't tell you the script is safe. A valid signature identifies who signed it, not whether its actions are appropriate.

PowerShell · freeze-artifact.ps1 Test before production
# Example from AI Field Manual. Provided as-is, without warranty.
# Read it, then test it in a non-production environment before any production use.

$path = 'C:\Review\cleanup-old-profiles.ps1'   # adjust locally
Get-Item -LiteralPath $path | Select-Object FullName, Length, LastWriteTime
Get-FileHash -LiteralPath $path -Algorithm SHA256
Get-AuthenticodeSignature -FilePath $path |
    Select-Object Status, StatusMessage, SignerCertificate

Record the hash in the ticket or change request. If the author sends a revised script, treat it as a new artifact that needs a new review. A file with the same name isn't necessarily the same code.

Step 2

Read without running

Open the file in an editor with line numbers. Inspect any companion .psm1 and .psd1 files, configuration files, and modules it imports at runtime. Search for side effects, but don't stop because "no dangerous keywords were found."

PowerShell · search-effects.ps1 Test before production
# Example from AI Field Manual. Provided as-is, without warranty.
# Read it, then test it in a non-production environment before any production use.

# Read-only inspection. None of these commands executes the reviewed script.
$path = 'C:\Review\cleanup-old-profiles.ps1'
Get-Content -LiteralPath $path -Raw
Select-String -LiteralPath $path -Pattern @(
    'Remove-Item', 'Set-', 'New-', 'Start-Process', 'Invoke-Command',
    'Invoke-Expression', 'iex', 'DownloadString', 'Invoke-RestMethod',
    'Invoke-WebRequest', 'Start-BitsTransfer', 'EncodedCommand',
    'Set-Content', 'Out-File', 'Export-', 'schtasks', 'sc.exe', 'reg.exe'
) -AllMatches

This is triage, not a security scan. Variables, aliases, reflection, dynamically built commands, external executables, imported functions and argument expansion can all hide effects. Equally, an alarming word may appear only in a comment. Confirm what each match actually does.

Parse without executing. PowerShell's own parser reports syntax errors and the abstract syntax tree (AST), which is much safer than importing or dot-sourcing unknown code:

PowerShell · parse-ast.ps1 Test before production
# Example from AI Field Manual. Provided as-is, without warranty.
# Read it, then test it in a non-production environment before any production use.

$tokens = $null; $parseErrors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile(
    'C:\Review\cleanup-old-profiles.ps1',
    [ref]$tokens, [ref]$parseErrors
)
$parseErrors | Select-Object Message, Extent
$ast.FindAll({ param($node)
    $node -is [System.Management.Automation.Language.CommandAst]
}, $true) | Select-Object -ExpandProperty Extent |
    Select-Object -ExpandProperty Text

The AST shows command expressions; it can't prove what a dynamically constructed command will eventually run. If the script runs a downloaded payload or a compiled binary, review that too.

Step 3

Run static checks and inventory the effects

If the module is already approved and installed, PSScriptAnalyzer can catch style and some correctness problems without running the script:

PowerShell · analyze.ps1 Test before production
# Example from AI Field Manual. Provided as-is, without warranty.
# Read it, then test it in a non-production environment before any production use.

Import-Module PSScriptAnalyzer
Invoke-ScriptAnalyzer -Path 'C:\Review\cleanup-old-profiles.ps1' |
    Select-Object RuleName, Severity, Line, Message

The analyzer isn't a malware detector or a formal proof. No warnings doesn't mean safe. See Microsoft Learn: PSScriptAnalyzer.

Then build this inventory. If you can't fill a cell, write Unknown, not None.

Category Questions to answer
File system Which paths are read, created, moved, deleted or searched recursively? Are they built from variables?
Identity and directory Does it enable, disable, change or enumerate users, groups, licenses, permissions, mailboxes or devices?
Network Which endpoints does it contact? Does it upload source, metadata or credentials?
Processes and services Can it start or stop processes, services, scheduled tasks or installers?
Privileges Which account and context does it need? Could it run with less access?
Dependencies Which modules, executables, environment variables and external resources must exist?
Error handling What happens if a command fails halfway? Are errors ignored? Could a retry repeat an action?
Output Where are logs, exports, transcripts, temporary files and any secrets written?
Step 4

Ask the AI for a threat-aware explanation

Give the model the sanitized code, the intended task and the target environment. Require it to cite line numbers or exact statements, and to admit what it can't see in imported dependencies.

The script review prompt
You are assisting a systems administrator with a static review of an
unfamiliar PowerShell script. The script has NOT been executed. I am
the decision-maker. Do not infer safety from comments or signatures.

INTENDED TASK: [precise desired outcome]
TARGET ENVIRONMENT: [Windows / PS version / server role / account]
SCRIPT HASH: [SHA-256]
SCRIPT OR EXCERPT: [sanitized, line-numbered source]
DEPENDENCIES: [known modules or "not yet reviewed"]

RETURN:
1. Plain-language summary of what the script does, by major stage.
2. Every potential side effect: file, identity, network, service,
   registry, scheduled task, external executable and module call.
3. Privileges and dependencies needed, with uncertainty labels.
4. A list of risky assumptions with exact line references.
5. Which actions might support -WhatIf and which definitely do not
   have a proven safe simulation path.
6. A test plan using a nonproduction target and a limited scope.
7. A go / hold / reject recommendation with reasons.

RULES: Never say a script is safe just because static analysis passed.
Do not invent behavior for unresolved functions. Do not execute code,
recommend bypassing defenses, or claim an external command honors
PowerShell -WhatIf without evidence. Prefer concise tables.

Treat the answer as a list of claims to audit. If it says "this deletes only user profiles older than 90 days," find the expression that computes the age and the exact deletion path. Is the cutoff based on LastWriteTime, real sign-in history or a stale registry value? Is the comparison inclusive? Is the target path held inside the intended root?

Step 5

Check the simulation and rollback assumptions

-WhatIf is valuable when a cmdlet or function implements ShouldProcess. It isn't a universal dry-run switch. A custom function can expose -WhatIf and still call an external executable that changes state anyway, and Start-Process can launch a program that makes changes even when another part of the pipeline supports -WhatIf. Read the help and the implementation before relying on it. See Microsoft Learn: ShouldProcess.

Execution policy isn't a security boundary. Setting it to Bypass doesn't make a suspicious script trustworthy. See Microsoft Learn: execution policies.

Verification sequence:

  1. Identify input paths and targets in a small, disposable test environment.
  2. Snapshot or back up the test state, and define the output you expect.
  3. Review dependencies and the execution identity. Don't grant broad production credentials for convenience.
  4. Confirm which actions support a reliable -WhatIf, and check that its output is complete.
  5. Run the script only in the approved, isolated test environment, after review and authorization.
  6. Compare the actual changes with what you expected. Test the failure and retry paths, not only success.
  7. Get change approval for production, with an operator, monitoring, abort criteria and rollback steps.

A promise to "restore from backup" isn't a rollback plan unless the restore procedure, access, time and scope have been tested.

Step 6

Worked example: the deceptively simple cleanup script

Fictional case. A script called archive-profiles.ps1 describes itself in its header as "moves old user folders into archive." The relevant excerpt:

PowerShell · archive-profiles.ps1 (excerpt, do not run) Test before production
01  $root = 'D:\Departments'
02  $archive = 'D:\Archive'
03  $cutoff = (Get-Date).AddDays(-90)
04  Get-ChildItem $root -Directory -Recurse |
05    Where-Object LastWriteTime -lt $cutoff |
06    ForEach-Object {
07      Move-Item $_.FullName (Join-Path $archive $_.Name) -Force
08    }

An AI might summarize this as "archives files older than 90 days." That's wrong. The script processes directories, tests the directory's LastWriteTime, and recurses into subdirectories. Nothing restricts it to top-level user folders. Two users with identically named subfolders would collide in the archive. There's no collision handling, logging, permission review or error recovery. A move across volumes behaves differently from a rename on the same volume, and -Force doesn't fix the design.

Finding: HOLD. Before any production run, require an explicit list of top-level target paths, a deterministic destination mapping, conflict handling, a dry-run listing, backups, and a tested retry and rollback procedure. That isn't an accusation that the script is malicious. It's evidence that, as written, it's unsuitable for its stated purpose.

Step 7

Record the decision

Script review record
Artifact: [file/repository/version]   SHA-256: [hash]
Purpose: [one sentence]               Owner: [team/person]
Environment: [hosts, role, PowerShell version, identity]
Provenance/signature: [observed, not a safety guarantee]
Summary: [what it does]
Reads: [paths / objects]              Writes/changes: [paths / objects]
External calls: [network / executables / modules]
Required permissions: [minimum justified]
Unresolved dependencies: [items]
Key hazards: [line references and severity]
Static checks: [parser / analyzer results]
Test evidence: [test target, date, observations]
Rollback evidence: [specific procedure and test result]
Decision: [GO / HOLD / REJECT]        Approver: [name/date]
AI assistance: [tool and approved data classification]
Human reviewer: [name/date]

What stays with you: whether the code runs, under which identity, against which objects, and whether your evidence satisfies your change policy.

Further reading on Microsoft Learn: the PowerShell parser API, PSScriptAnalyzer, ShouldProcess.

Esc

Saved in this browser

Reading list

Contents

Reference

Keyboard shortcuts

/ or Ctrl K
Search the manual
↑ ↓
Move through search results and index entries
Enter
Open the selected result
← →
Switch discipline tabs; previous / next entry in a workflow card
Esc
Close any dialog
?
Show this list