Nine PowerShell Habits That Pass Code Review and Fail at 3 A.M.
Photo: Rubin Observatory/NSF/AURA, CC BY 4.0, via Wikimedia Commons
There's a particular kind of PowerShell bug that never shows up in a dev environment. The script ran fine when you hit F5. It ran fine when a colleague tested it in a console. Then it went into a scheduled task running as a service account at 2:45 in the morning and started doing something creative with your data.
None of the habits below are syntax errors. Every one of them passes review. Every one of them has bitten somebody on my watch.
1. Relative paths
The habit: Get-Content .\config.json — because the file is right there, next to the script.
How it breaks: A scheduled task, a Runbook, or a WinRM session sets the working directory to C:\Windows\System32 or somewhere equally useless. The script either dies or, worse, picks up a completely different file with the same name.
The fix: Anchor everything to the script itself.
$root = $PSScriptRoot
$config = Join-Path -Path $root -ChildPath 'config.json'
And use -LiteralPath rather than -Path whenever a path came from a variable — square brackets and wildcards in a folder name will otherwise be interpreted, not matched literally.
2. Depending on your profile
The habit: Never importing modules because they're already in your session, and relying on an alias you defined years ago.
How it breaks: Scheduled tasks, -NoProfile, and remoting endpoints don't run your profile. Every function, alias, and module you assumed was loaded evaporates.
The fix: #Requires -Modules ActiveDirectory, SqlServer at the top, plus explicit Import-Module -Name X -ErrorAction Stop inside the script. If a dependency goes missing, fail at line three, not line four hundred.
3. Write-Host as a logging framework
The habit: Progress and status updates sprayed with Write-Host.
How it breaks: Write-Host doesn't go to the success stream. You can't capture it, redirect it to a file with > (not in the way you expect), or assert against it in Pester. Audit logs vanish.
The fix: Emit Write-Information with tags for anything a human should see, Write-Verbose for diagnostic noise, and structured objects for data. If you truly need transcript-style output, redirect the information stream explicitly.
4. Silencing errors instead of handling them
The habit: -ErrorAction SilentlyContinue bolted onto every cmdlet, plus a try/catch around the whole script body.
How it breaks: Non-terminating errors don't throw. Your catch block never fires, the script reports success, and the missing 4,000 users go unnoticed until somebody reconciles the headcount at month end.
The fix: Set $ErrorActionPreference = 'Stop' at the top of the script — scoped, not global — or pass -ErrorAction Stop deliberately where you want termination. Capture -ErrorVariable when you need the failures for a report. Then test the failure path; every serious incident I've seen involved a catch nobody had ever executed.
5. Assuming the caller's identity
The habit: $env:USERNAME, $env:USERPROFILE, mapped drive letters, and HKCU: lookups.
How it breaks: Under a service account, that's the service account's profile. Mapped drives are per-session and per-user; a drive letter that exists in your RDP session doesn't exist in a task's session. HKCU points somewhere entirely different.
The fix: Use [Security.Principal.WindowsIdentity]::GetCurrent().Name when you need the actual identity, UNC paths instead of mapped letters, and explicit registry hives (HKLM:, or a loaded hive for user-scoped data). If you need the logged-on interactively user rather than the process owner, query it — don't guess from an environment variable.
6. Date comparisons as strings
The habit: Get-Date -Format 'MM/dd/yyyy' and then comparing those strings.
How it breaks: String comparison and date comparison are unrelated. A locale change on the host reorders the parts. Sorting a folder of files named by formatted date gives you a mixed order that quietly stops your incremental sync.
The fix: Keep dates as [datetime] objects for logic and only format at the boundary. When you must serialize, use ISO 8601 via -Format 'o' or [datetime]::ParseExact with InvariantCulture. Round-trip [datetime]::Parse will respect the host culture, which is not something you want in a script that runs on forty servers.
7. Recursive enumeration with no guardrails
The habit: Get-ChildItem -Path C:\ -Recurse to find files modified recently, then Get-Content on whatever it finds.
How it breaks: It traverses the profile directories, the Windows component store, and any junction it can reach. A four-gigabyte log file gets read fully into memory inside the loop. The task times out or the server starts swapping.
The fix: Scope the search, use -Filter (which filters at the provider level) rather than -Include, and stream large files with [System.IO.File]::ReadLines(). Add a timeout and a progress counter so the run is observable.
8. Invoke-Expression on a built string
The habit: Assembling a command from variables and running it through Invoke-Expression because it was easier than figuring out the quoting.
How it breaks: Anything in a variable becomes code. It also fails outright in Constrained Language Mode, breaking in exactly the environments where you can't debug it easily.
The fix: Splatting and the call operator with argument arrays:
$params = @{
Path = $target
Destination = $dest
Force = $true
}
Copy-Item @params
& $exe @('--input', $path, '--mode', 'safe')
Both forms pass values, not source code. That distinction matters in any environment running AppLocker or WDAC.
9. Inconsistent output types
The habit: A function that returns a single object when there's one result and an array when there are several.
How it breaks: $result.Count throws or returns nonsense on a single object in older hosts, and downstream foreach behaves differently depending on how many rows happened to exist that day.
The fix: Always wrap returns in @() or emit [pscustomobject] consistently. Then document the shape so the next person doesn't have to reverse-engineer it from call sites.
None of these require heroics. They require the assumption that your script will run somewhere you've never logged into, as someone you've never met, with a working directory you didn't choose. Write for that, and the 3 A.M. page stays quiet.