Claude Code Hooks on Windows: Shells, Exit Codes and UTF-8
Claude Code hooks on Windows run through Git Bash unless you configure them otherwise, and a hook blocks a tool call only when its process exits with exactly 2. Most Windows hook failures I tested or read about fail open: a PowerShell exit 2 that comes out as 1, a guard that reads mangled UTF-8 and matches nothing, a path check comparing C:\ with /c/. Below: one PreToolUse guard in Windows PowerShell 5.1, PowerShell 7, Git Bash and Node, what I measured for each on Windows 11, and the setup I would use now.
What I ran, and what I did not. I fed the hook scripts JSON on stdin from a Node launcher of my own on 2026-10-13, with Claude Code 2.1.296 installed but not running. Statements about Claude Code itself, such as which shell it starts or whether exit 2 stops the call, come from the official docs and are marked. On 2026-10-21 I also ran 14 real Claude Code sessions on Claude Code 2.1.306, Windows 11, with claude-haiku-5-5 and one tool call each. I wrote the script and read every output file; the admin agent ran it under a test login. Those results are marked "in Claude Code". Not run: whether hooks flash a console window, which needs an interactive session.
Which Shell Runs a Hook on Windows
This section is from the docs, then checked on 2026-10-18 in Claude Code 2.1.302 on Windows 11. A model call was not possible in that run, so the hooks used the UserPromptSubmit event, which fires before any API call and starts hooks the same way. The 2026-10-21 runs below used PreToolUse. The hooks reference describes two forms of command hook:
- Shell form, no
args: "Thecommandstring is passed to a shell:sh -con macOS and Linux, Git Bash on Windows, or PowerShell when Git Bash isn't installed." - Exec form, with
args: Claude Code spawnscommanddirectly withargsas the argument list. "There is no shell." - The
shellfield takes"bash"or"powershell". For PowerShell the docs say Claude Code "auto-detectspwsh.exe, the PowerShell 7 and later executable, and falls back topowershell.exe".
Two open issues disagree: #90077 reports that "shell": "powershell" starts pwsh with no fallback, so without PowerShell 7 and Git Bash the hook never runs, and #90495 reports exec-form args dropped and the hook started as bash.exe -c node on 2.1.117. What I saw on 2.1.302:
- Shell form started Git Bash:
node.exeunderbash.exe -cunderclaude.exe.CLAUDE_PROJECT_DIRhad forward slashes,C:/Users/.... "shell": "powershell"startedpwsh.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command, so PowerShell 7 was chosen here, andCLAUDE_PROJECT_DIRhad backslashes. Whether it falls back topowershell.exewhenpwshis missing (#90077) I did not test: that needspwshuninstalled.- Exec form started
node.exedirectly underclaude.exe, with no shell. The arguments were kept and${CLAUDE_PROJECT_DIR}was expanded, so I could not reproduce #90495 on this version.
The test folder had a space and an accented letter in its path, café real.
The shell your hook runs in is separate from the shell Claude runs commands in. Per the PowerShell tool notes, wherever the PowerShell tool is enabled on Windows, Claude routes shell commands through it, and without Git Bash the Bash tool is not registered at all: "A hook that matches only Bash never fires there." Match both with "matcher": "Bash|PowerShell".
The docs' Windows config shape, with my guard:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell",
"hooks": [
{
"type": "command",
"command": "powershell.exe",
"args": ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.ps1"]
}
]
}
]
}
}
How I Tested the Scripts
My launcher spawns each hook with windowsHide set, writes a payload with the documented PreToolUse fields to stdin as UTF-8 without a byte order mark, and records exit code, stdout, stderr and time. For shell form it runs bash.exe -c "<command>", my stand-in, not necessarily Claude Code's exact call. The project folder was %TEMP%\hook lab\café project, with a space and a non-ASCII letter on purpose.
Versions: Windows PowerShell 5.1.26100, PowerShell 7.6.6, Node 25.2.1, GNU bash 5.2.37 from Git for Windows, Python 3.14.2. Console code page 850, ANSI code page 1252.
A Guard That Blocks rm -rf
The guard reads the payload, looks at tool_input.command and exits 2 with a reason on stderr when it finds rm -rf. This is guard.ps1, the version that passed every case below in both PowerShell versions:
# guard.ps1: PreToolUse guard for Bash and PowerShell tool calls.
# Blocks any command that contains "rm -rf" by writing a reason to stderr and exiting 2.
# Reads stdin as UTF-8 bytes, so non-ASCII text survives on Windows PowerShell 5.1 too.
$ErrorActionPreference = 'Stop'
try {
$reader = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), [System.Text.UTF8Encoding]::new($false))
$payload = $reader.ReadToEnd() | ConvertFrom-Json
if ($null -eq $payload) { throw 'empty input' }
$command = [string]$payload.tool_input.command
} catch {
[Console]::Error.WriteLine("guard.ps1 could not read the hook input: $($_.Exception.Message)")
exit 2 # fail closed: an unreadable payload blocks the call
}
if ($command -match 'rm\s+-rf') {
[Console]::Error.WriteLine('Blocked by guard.ps1: rm -rf is not allowed here')
exit 2
}
exit 0
The Node version, guard.mjs, does the same and is the one I would pick (startup times are further down):
// guard.mjs: PreToolUse guard for Bash and PowerShell tool calls.
// Blocks any command that contains "rm -rf" by writing a reason to stderr and exiting 2.
import { readFileSync } from 'node:fs';
let command;
try {
let raw = readFileSync(0, 'utf8');
if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1); // drop a byte order mark
command = String(JSON.parse(raw).tool_input?.command ?? '');
} catch (err) {
process.stderr.write(`guard.mjs could not read the hook input: ${err.message}\n`);
process.exit(2); // fail closed
}
if (/rm\s+-rf/.test(command)) {
process.stderr.write('Blocked by guard.mjs: rm -rf is not allowed here\n');
process.exit(2);
}
process.exit(0);
Results, for a payload with rm -rf build, one with npm test, invalid JSON and empty stdin:
powershell.exe -File guard.ps1andpwsh -File guard.ps1: 2, 0, 2, 2. Stderr:Blocked by guard.ps1: rm -rf is not allowed here.node guard.mjs: 2, 0, 2, 2.bash guard.sh: 2, 0, 0, 2. Git for Windows ships nojq, which the docs' bash examples use, so my bash guard matches the raw JSON with a regex and lets invalid JSON through.
My first PowerShell guard exited 0 on empty stdin: ConvertFrom-Json returned nothing without an error. The $null check comes from that run.
Exit Codes: Only 2 Blocks
What Claude Code does with each exit code is from the docs, and I checked it in Claude Code 2.1.306 (results below). Exit 0 is success. Exit 2 blocks a PreToolUse call, and stderr becomes the reason Claude sees. Any other code is a non-blocking error and the action goes ahead: "Without valid JSON on stdout, Claude Code treats exit code 1 as a non-blocking error, even though 1 is the conventional Unix failure code." A timed-out hook does not block either.
In Claude Code, with the model asked to run rm -rf scratch-dir in a Bash tool call and a guard on PreToolUse:
node guard.mjs,powershell.exe -File guard.ps1andpwsh -File guard.ps1, all exec form: exit 2, the call was blocked and the folder was still there. Claude sawPreToolUse:Bash hook error: [node ${CLAUDE_PROJECT_DIR}/and stopped without trying another way..claude/hooks/ guard.mjs]: Blocked by guard.mjs: rm -rf is not allowed here powershell.exe -Command "& 'guard.ps1'": the script printed its reason and Claude Code logged status 1. The call went through and the folder was deleted. This is the trap below, now seen inside Claude Code.- The
$inputtrap: status 0, the folder was deleted. "command": "bash"withargs: it depends onPATH. On 2.1.306 the hook never started. The debug log saysExecutable not found in $PATH: "bash", and the call went through. Claude Code's own Bash tool found Git Bash atC:\Program Files\Git\bin\bash.exein the same run, so a name that works as the tool's shell is not a name your hook can spawn. I did not record the PATH of that run. On 2.1.310 I recorded it: withC:\Program Files\Git\usr\binonPATHthe same hook started, exited 2 and blocked the call. With every Git folder removed fromPATHit failed to spawn again, and therm -rfran. Git was still installed in both runs, and Claude Code found its own Git Bash either way. A hook that cannot start is not a block. Use shell form for a.shscript, or name the interpreter with a full path.
So every PowerShell path that ends in exit 1 is a guard that does nothing. Measured outside Claude Code with the blocking payload:
-Command "& 'guard.ps1'": 1 in 5.1 and 7, though the script ranexit 2and printed its reason. Issue #24757, closed as stale, reported 0; either way it does not block.-Command "& 'guard.ps1'; exit $LASTEXITCODE": 2.throwinstead ofexit 2: 1.- The docs' read pattern with
$ErrorActionPreference = 'Stop'and invalid JSON: 1. WithoutStop: 0. - A script path that does not exist:
powershell.exeexited 4294770688 (0xFFFD0000) and printed its copyright banner to stdout;pwshexited 64. - No
-ExecutionPolicy Bypass: 2 here, but that depends on the machine's policy, so keep the flag.
The missing script matters with "onFailure": "block" (2.1.295 or later), which exists so a broken hook blocks. Open issue #100891 reports that Claude Code counts the 0xFFFD0000 exit as success. My exit code matches that report, and on 2.1.302 so does Claude Code's behaviour: with powershell.exe -File missing.ps1 and onFailure set to "block", the hook finished with status 0 and the prompt went on to the API. The docs say a failed hook blocks, so for this case they overstate it. With node missing.mjs in exec form the same setting did block: failed; blocking because onFailure is "block". I tested both on a UserPromptSubmit hook on 2.1.302, and again on PreToolUse on 2.1.306 with the same result: the node case blocked the Bash call, and the powershell.exe -File case finished with status 0 and the call ran (ls listed the folder). If your guard is a PowerShell script, start it with node or check that the file exists; do not rely on onFailure alone.
The $input Trap
This one fooled my own test script first: its encoding probe read an empty string in every mode but one. If a script mentions $input anywhere, even in a branch that never runs, PowerShell reads stdin before the first line executes, and [Console]::In.ReadToEnd() returns nothing. One debug line at the top of a working guard:
if ($env:HOOK_DEBUG -eq 'stdin') { $input | Out-File "$env:TEMP\hook-stdin.txt" }
HOOK_DEBUG was not set, and the guard exited 0 on the rm -rf payload in 5.1 and 7. Without the line, 2. A probe saw 91 characters without the mention and 0 with it.
UTF-8 In, UTF-8 Out
The hooks reference does not say what encoding the stdin JSON uses. Open issue #96285 reports raw UTF-8, and on 2.1.302 I confirmed it: the bytes Claude Code sent for the prompt echo café 日本語 were UTF-8 with no BOM (63 61 66 c3 a9 for "caf" and "é"). That was a UserPromptSubmit payload, not a Bash command. For my own tests I sent UTF-8 without a BOM, with this command in the payload: echo 'café 日本語 ✓' > notes.txt.
[Console]::In.ReadToEnd(), the read in the docs' PowerShell example, and$input:cafébecamecaf├®and the Japaneseµùѵ£¼Þ¬×, in 5.1 and 7. Both decode with the console code page, 850 here. Thecwdfield was mangled too.- A UTF-8
StreamReaderover[Console]::OpenStandardInput(), as inguard.ps1, or setting[Console]::InputEncodingfirst: correct. - Node with
readFileSync(0, 'utf8'): correct. - Python
sys.stdin.read():café(cp1252). Decodingsys.stdin.bufferasutf-8-sig: correct. My first Python run looked fine only because my shell setsPYTHONIOENCODING=utf-8. - Bash passed the bytes
c3 a9through unchanged.
With a BOM in front, Node's JSON.parse failed with Unexpected token '\ufeff' and PowerShell's ReadToEnd() plus ConvertFrom-Json failed; the StreamReader and utf-8-sig reads were fine. Both guards handle a BOM.
Output too: a deny decision from ConvertTo-Json with the reason Blocked: café folder is read-only wrote é as the byte 0x82, code page 850, invalid in UTF-8, so my launcher read caf�. Setting [Console]::OutputEncoding to UTF-8 fixed it. The JSON still parsed; only the reason text was damaged.
In Claude Code, a Node hook that wrote Blocked: café folder is read-only as UTF-8 to stderr with exit 2 reached Claude intact, accent included. So did the same text in a JSON deny on stdout with exit 0 (permissionDecision: "deny" and permissionDecisionReason); Claude Code showed it as PreToolUse:Bash hook error: Blocked: café folder is read-only. Both blocked the call. The damage above comes from the PowerShell output encoding, not from Claude Code.
And Windows PowerShell 5.1 reads a .ps1 saved as UTF-8 without a BOM as ANSI: a literal 'café' came out as café. Keep hook scripts ASCII.
Paths with Spaces and Backslashes
The docs say tool_input.file_path "arrives with backslash separators, even when your hook runs under Git Bash where $PWD looks like /c/project". I captured it from Claude Code 2.1.306 on a Write call in the folder café real: file_path was C:\Users\xndr\...\café real\sub dir\new file.txt, with backslashes, the space and the accent intact, and cwd and CLAUDE_PROJECT_DIR (exec form) were backslash paths too. With such a path in my own payload, the bash check printed:
PWD=/tmp/hook lab/café project
file_path=C:\Users\xndr\AppData\Local\Temp\hook lab\café project\src\index.ts
cygpath -w PWD=C:\Users\xndr\AppData\Local\Temp\hook lab\café project
naive inside=no
cygpath inside=yes
Git Bash mounts the temp folder as /tmp, so $PWD did not even start with /c/. A guard that allows "files under $PWD" would deny every edit, as open issue #94256 reports. Convert with cygpath -w and compare case-insensitively. PowerShell's StartsWith($cwd + '\', 'OrdinalIgnoreCase') on the payload's cwd and Node's path.relative both worked.
Shell form is where spaces and backslashes break. Through bash.exe -c, with a space in the guard's path:
node C:\...\guard.mjs, unquoted: exit 1. Bash ate the backslashes.node C:/.../guard.mjs, unquoted: exit 1,Cannot find module 'C:\Users\xndr\AppData\Local\Temp\hook', cut at the space.- Either one in double quotes, or exec form with the path in
args: exit 2.
Open issues #93356 and #101311 report the same split inside Claude Code itself, for Windows user names with a space.
Want more like this?
New posts in your inbox, a few a month.
How Long a Hook Takes to Start
A PreToolUse hook adds its startup time to every matching tool call. I timed a hook that reads stdin and exits 0: a warm-up, then five runs, in three batches. Other work was running, and CPU load read 100% right after the last batch, so read this as an order, not a benchmark. Ranges of the three medians:
node noop.mjs: 59 to 168 ms.bash.exe -c "node noop.mjs": 223 to 448 ms.powershell.exe -NoProfile -File: 285 to 373 ms.bash.exe noop.sh: 429 to 699 ms.pwsh -NoProfile -File: 1,444 to 2,743 ms.
Node was fastest and PowerShell 7 slowest in every batch. I would not call the pwsh figure typical.
Console Windows
Inside a PowerShell hook started by my launcher with windowsHide, GetConsoleWindow() returned 0: no console window. That says nothing about how Claude Code starts hooks: my Claude Code runs were headless, so I could not see a window either way. Issue #27115, closed as stale, reported flashing console windows on 2.1.45. Open issue #95673 reports that a bare .sh path as the command opens git-bash.exe through the file association, in its own window and without the hook's stdin. Name the interpreter: bash "path/to/hook.sh".
The Setup I Would Use Now
- Exec form, the script path in
argsafter${CLAUDE_PROJECT_DIR}. - Node where possible: fastest, and correct UTF-8 with no extra code. Check that
nodeis on the PATH; the setup docs say the installedclaudebinary "does not itself invoke Node". - In PowerShell:
-File,exit 2and neverthrow, a UTF-8StreamReader, no$input. - Exit 2 when parsing fails, so bad input blocks.
- Match
Bash|PowerShell; compare paths in Windows form. - Pipe sample JSON into the script and check
$LASTEXITCODEbefore trusting it.
I build agent setups like this for teams; see our services. For the unattended side, see running Claude Code as an always-on agent on Windows; hooks are where its guard rails belong.
What I Have Not Run
Two passes in Claude Code. On 2026-10-18 (2.1.302, no model call) I checked which process starts for shell form, "shell": "powershell" and exec form, the stdin bytes, and onFailure with a missing script. On 2026-10-21 (2.1.306) I ran 14 sessions with a real model call each: exit 2 blocks, the -Command wrapper and the $input trap do not, a hook that cannot start does not, the deny reason keeps its accent, and the file_path arrives with backslashes. On 2026-10-26 (2.1.310) I repeated the 14 sessions and added two with Git removed from PATH: the results matched 2.1.306, except that the exec-form bash hook now started because bash was on PATH in that run. The 2.1.309 and 2.1.310 changelog entries about PowerShell hooks that exit 2 and hooks that let a call through when Git for Windows is missing are not something I reproduced: exit 2 already blocked on 2.1.306 in the forms I tried, and Git for Windows stayed installed. Not run: console windows (a headless run cannot show one), whether "shell": "powershell" falls back to powershell.exe without PowerShell 7, a machine with no Git for Windows, other Claude Code versions, and anything on macOS or Linux. One run per case: a model chose to make the tool call each time, so treat each result as one observation, not a rate.
FAQ
Which shell does Claude Code use to run hooks on Windows?
Per the docs, Git Bash for a hook without args, or PowerShell when Git Bash is not installed. Set "shell": "powershell" to choose PowerShell, or add args to start the program directly with no shell. On 2.1.302 I saw the same: Git Bash for shell form, no shell for exec form, pwsh for "shell": "powershell" when PowerShell 7 is installed.
Why does my PowerShell hook not block the tool call?
Usually because its process does not exit with 2. In my tests -Command "& 'script.ps1'" turned the script's exit 2 into 1, and throw also gave 1, which the docs treat as non-blocking. Run the script with -File, or end the command with ; exit $LASTEXITCODE.
Why does my hook see text like caf├® on Windows?
The hook decoded UTF-8 input with the console code page. In PowerShell, read stdin through a StreamReader with UTF-8, or set [Console]::InputEncoding first. In Python, decode sys.stdin.buffer as UTF-8. Node's readFileSync(0, 'utf8') was correct as it is.
Does exit code 1 block a Claude Code hook?
No. The docs call exit 1 a non-blocking error and the action goes ahead. Only exit 2 blocks, on events that can block, such as PreToolUse. A JSON decision on stdout with exit 0 is the other way to deny.
How do I write one hook that works in Git Bash and PowerShell setups?
Use exec form with "command": "node" and the script path in args, and match Bash|PowerShell. No shell parses the command, so quoting, backslashes and spaces in the path stop mattering.
Related Articles
- Running Claude Code as an Always-On Agent on Windows: the scheduler and supervisor side.
- Using Claude Code to Diagnose and Fix Windows System Issues: more Windows-first notes.
- Fixing the Claude Code Chrome Extension on Windows: another Windows-only failure.
- XNDR services: we design and build AI agents and the automation around them.
Liked this one? Get the next in your inbox.
New posts and the odd product note, a few emails a month. Easy to leave.