How do I check whether an SSH command succeeded in CMD or PowerShell?
SSH returns the exit status of the remote command when it can run it; connection or SSH-level failures generally return 255. Read the native exit code immediately after the command. A printed message alone is not a reliable success test.
Instructions
1. Run a bounded read-only command
Use a known Linux server and an authorised account. The hostname command exits without opening an interactive shell.
ssh adminuser@203.0.113.10 hostname
$LASTEXITCODEPowerShell stores the native program result in $LASTEXITCODE. Read it before another native program changes it.
2. Use the CMD status variable
In a batch file, avoid accidentally expanding the variable before the SSH command runs inside a parenthesised block.
ssh adminuser@203.0.113.10 hostname
echo %ERRORLEVEL%These are separate CMD lines. Zero indicates this command reported success.
3. Interpret the result in context
A nonzero remote exit code may reflect a failed Linux command rather than a network problem. If SSH reports 255, inspect the accompanying error for host verification, routing or authentication failure. Preserve both output and status in automation.
Check the result
- The returned hostname matches the intended server.
- The immediately captured exit code is zero for the successful hostname command.
Troubleshooting
- PowerShell shows True but the command failed
- Use $LASTEXITCODE for the native SSH result; PowerShell success semantics vary with context and version.
- The status changes later
- Another native program can replace it. Assign it to a task-specific variable immediately if subsequent work needs it.
Official references
Use the documentation for your installed version when a flag, service name or platform feature differs.
