A bash script that has run for years on Linux often fails within seconds on Windows 11. The shebang points nowhere, a familiar listing flag returns an unknown parameter, and the log opens as mojibake in Notepad. The logic was rarely wrong. The machinery around it changed: command names, quoting, error handling, path syntax, and a pipeline that moves objects instead of lines. The differences are finite, and each has a working equivalent.
The Different Data Models of the Two Shells
In bash every command is a separate program, and the only contract they share is a stream of bytes. Text is the interface: grep reads lines, awk splits fields, sed rewrites them. PowerShell keeps the pipe character and replaces bytes with .NET objects. A directory listing hands the next stage file objects that already know their size, timestamp, and extension, so a filter tests a property instead of a pattern.
The choice shows up daily. A pipeline that lists files and greps for a suffix becomes a filtered listing with a property test; the alias ls accepts -Force but not -la. Aliases cover muscle memory, not parameters, so cat -n, rm -rf, and cp -r fail against cmdlets that expect separate switches.
Two hosts matter. Windows 11 ships Windows PowerShell 5.1 as powershell.exe, and PowerShell 7.x installs as pwsh.exe. The version table reports the engine, and a requires line states the minimum. Version 5.1 lacks the null-coalescing and ternary operators and writes text as UTF-16 by default.
Aliases also mislead. In 5.1, curl resolves to Invoke-WebRequest, so a quiet flag fails while curl.exe reaches the real binary. PowerShell 7 dropped that alias, yet checking the command source first is still wise.
Variables, Quoting, and Expansion in Matched Pairs
Assignment looks similar until the first collision. Bash needs name=value with no spaces, and a space turns the line into a command. PowerShell accepts spaces around the equals sign and ignores case, so $Path and $path are one variable. That tolerance costs: $Host, $PID, $args, and $Error already mean something, and assigning to the host object throws. A script that names a variable host needs a rename, not a syntax fix.
Single quotes stay literal and double quotes expand in both shells, which makes quoting the easy part. The escape character differs, backslash in bash and backtick in PowerShell. Inside double quotes PowerShell expands simple variables only, so a member access needs a subexpression: "$file.Name" appends literal text, while "$($file.Name)" evaluates the property. Braces merely delimit a name, which means the bash default-value form is not an operator here.
Arrays differ where it matters. Bash writes tags=(prod eu-west batch) and expands the whole array with its at-sign form; PowerShell writes an at-sign list and expands it by name, or joins the values when output needs one string. A single result from a cmdlet is not an array unless wrapped in the array operator, which explains most count surprises. Environment variables are process scoped: an export becomes an env assignment, and the value vanishes when the host exits.
Multiline text moves from heredocs to here-strings. A bash heredoc starts after a double redirect and ends with a delimiter on its own line; a PowerShell here-string opens with an at-sign and a quote that must end its line, and closes with a matching pair at the start of a line. A single-quoted here-string suppresses expansion, which matches the quoted heredoc.
Strict mode is the closest match for set -u. It flags uninitialized variables and bad property access, but it does not stop a failing native program.
set -euo pipefail
host="web01"
report="/var/log/app/${host}-$(date +%F).txt"
printf 'report=%s\n' "$report"
#Requires -Version 7.0
$hostName = 'web01'
$report = Join-Path 'C:\Logs\App' "$hostName-$(Get-Date -Format 'yyyy-MM-dd').txt"
"report=$report"
Two decisions hide in that pair. The shebang disappears because the .ps1 extension already associates the file with the engine, and $host becomes $hostName because the original name is reserved. The date expression survives the move because bash runs a command substitution and PowerShell evaluates a subexpression inside double quotes.
Pipelines That Carry Objects Rather Than Lines
Line-oriented commands have object-oriented counterparts: head becomes Select-Object -First, tail becomes -Last, grep becomes Select-String, and a line count becomes Measure-Object. The mapping is not mechanical, since each cmdlet returns a different type.
Inside the pipeline, the current object is $_. A recursive listing filtered on a size property compares bytes that awk would have had to parse, and Select-Object can add a calculated column without touching text.
xargs gives way to ForEach-Object. Bash substitutes a filename into a command line and worries about spaces; PowerShell passes the object, so a compression call inside the loop needs no quoting even when a path contains a space.
One rule prevents broken scripts. Format-Table and Format-List emit formatting objects rather than data, so they belong at the end of a pipeline. Processing stages select properties, and text output goes through Out-String.
A path-based search reads files directly and returns objects with line numbers, beating a line-by-line loop. ForEach-Object -Parallel exists for heavy work, though overhead usually favors a plain loop.
log_dir="/var/log/app"
find "$log_dir" -type f -name '*.log' -mtime +7 -print0 |
while IFS= read -r -d '' f; do gzip -9 "$f"; done
$cutoff = (Get-Date).AddDays(-7)
Get-ChildItem C:\Logs\App -Filter *.log -File -Recurse |
Where-Object LastWriteTime -lt $cutoff |
ForEach-Object { Compress-Archive $_.FullName "$($_.FullName).zip" }
Both versions compress every file older than a week, yet only the second compares timestamps as DateTime values. The bash side lets find evaluate the age and passes filename strings to gzip. That is the pattern to watch during a port, because it separates a script that parses output from one that reads properties.
Conditions, Loops, and Exit Codes That Survive a Port
Conditions are where silent bugs enter. Bash writes [ "$count" -gt 10 ]; PowerShell writes if ($count -gt 10). The operators read alike, but -eq compares strings case-insensitively unless the left side is a number, so a lowercase copy equals an uppercase one and -ceq restores case. The symbols < and > mean redirection, and a bare comparison inside parentheses creates a file instead of comparing values.
File tests map cleanly: a leaf test becomes Test-Path -PathType Leaf, and a container test becomes -PathType Container. Pattern matching splits into -like for wildcards and -match for regular expressions, with captures in $Matches. A case block becomes switch -Wildcard or -Regex, and unlike bash, PowerShell falls through unless a branch ends with break.
Loops translate almost one to one: a C-style for loop keeps its shape, while read becomes foreach over Get-Content, and until becomes do until. The break and continue keywords keep their meanings.
Functions carry the largest gap. A bash function returns a status and writes results to stdout; a PowerShell function returns everything written to the output stream. A stray Write-Output 'done' becomes part of the return value and corrupts the caller. Helpers should return values deliberately, send messages to the error stream, and let the script set the exit code.
$? is a boolean about the last command, while $LASTEXITCODE holds the numeric code of the last native program. A wrapper checks the numeric code and exits with it; an unhandled error exits with 1. trap becomes try, catch, and finally, and the exception message rides on $_.Exception.Message.
set -euo pipefail has no single switch. The closest mix is Set-StrictMode -Version Latest, $ErrorActionPreference = 'Stop', and, on 7.4 or newer, $PSNativeCommandUseErrorActionPreference = $true, which extends that behavior to native programs.
clean() {
local dir=${1:-}
[ -d "$dir" ] || return 3
find "$dir" -name '*.tmp' -delete
}
clean "${1:-}"
exit $?
param([string]$Path)
function Invoke-Clean {
param([string]$Directory)
if (-not $Directory) { return 3 }
if (-not (Test-Path $Directory -PathType Container)) { return 3 }
Get-ChildItem $Directory -Filter *.tmp -File -Recurse | Remove-Item -Force
return 0
}
$code = Invoke-Clean -Directory $Path
exit $code
Both blocks return code 3 for a missing directory, and the PowerShell version exposes the pitfall that catches most ports: return 3 inside a function writes the number 3 to the output stream, not to the process status. The script has to capture that value and pass it to exit. A helper that also printed progress text would return an array, and the comparison would fail.
Paths, External Tools, and the Encoding Traps
Path strings deserve their own pass. Join-Path inserts the right separator, Split-Path with -Leaf, -Parent, and -Extension replaces the bash prefix and suffix tricks, Resolve-Path makes a path absolute, and Test-Path answers existence questions. PSScriptRoot anchors script data files and is empty in an interactive session. A path assembled with string concatenation and a forward slash may work in bash and fail in PowerShell, so build every path with Join-Path.
PowerShell accepts forward slashes for its own cmdlets, so bash path literals often survive unchanged. Native programs are less forgiving, and an older utility expects backslashes. The tilde expands in path arguments, and $env:TEMP replaces /tmp.
Encoding is the quiet failure. In 5.1, redirection and Out-File write UTF-16LE, so a file read later by a bash tool looks like binary. PowerShell 7 defaults to UTF-8 without a byte order mark, and 7.4 passes the raw bytes of native output through redirection. A script that feeds other tools should state -Encoding utf8NoBOM and expect CRLF line endings.
Calling a program needs the call operator when the path is quoted: & 'C:\Program Files\Git\bin\bash.exe' -lc 'echo ok'. Output arrives as strings, and the status lands in $LASTEXITCODE. Start-Process -Wait -PassThru returns an object with an exit code property. Argument passing follows $PSNativeCommandArgumentPassing, whose Windows default is Windows: the Standard mode for most executables, with Legacy used only for a short list of old Windows tools such as cmd.exe and .bat or .cmd scripts.
Native PowerShell or a WSL Session for the Legacy Script
Three routes exist for a script that must run on Windows 11: rewrite it in PowerShell, run it through WSL, or run it through a POSIX layer such as Git Bash. Each has a cost that is easy to underestimate.
The triage that works asks four questions:
- whether the script must touch Windows services, the registry, scheduled tasks, or event logs, which favors native PowerShell;
- whether it depends on awk, sed, find with printf, or xargs with null delimiters, which favors WSL because those tools behave as documented;
- whether it runs unattended on a schedule, where a native call from Task Scheduler is simpler to audit than a WSL session;
- whether anyone will maintain the result, since a faithful port nobody can read is worse than a wrapper everyone understands.
WSL 2 runs a real Linux kernel, so scripts that need GNU find or a specific glibc build behave as they do on a server. wsl --install sets up a distribution, wsl -l -v lists versions, and wsl -d Ubuntu --exec /srv/app/deploy.sh starts a program directly. Going through bash -lc loads the profile and may change PATH, which matters when a tool comes from a version manager. Exit codes cross the boundary through $LASTEXITCODE, so a scheduled wrapper reports what Linux reported.
Windows files are reachable under /mnt/c, but access is slow for repositories with many small files. Keeping the working copy in the Linux filesystem and opening it through the wsl.localhost share avoids the penalty, while wslpath converts paths both ways.
Git Bash covers the middle ground without a kernel. The bash.exe binary inside the Git installation runs MSYS2 tools, which handle sed and awk for text work but translate paths as /c/App and surprise programs that expect Windows arguments.
The decision is made by maintenance, not syntax. A short script that copies files and calls one Windows tool is cheaper to rewrite, and the rewrite shrinks because the object pipeline removes parsing. A large deployment script built on GNU tools is cheaper to wrap, and the wrapper should pass the exit code through unchanged. The honest test is a run through the failure paths: a missing directory, an unreadable file, a tool that returns 3, a log line that survives UTF-8. Syntax translation takes an afternoon; behavior translation is the work that keeps the script useful.