출력 문장이 성공 판정을 바꿀 수 있습니다
외부 프로그램을 호출한 뒤에는 $LASTEXITCODE를 즉시 별도 변수에 저장하세요. $?는 마지막 명령의 성공 여부이므로 뒤에 실행한 로그 출력의 결과를 나타낼 수 있습니다. 마지막 화면에 완료 문장이 보인다고 앞선 프로그램이 성공한 것은 아닙니다.
이 글은 Windows PowerShell이라는 제품 이름의 5.1이 아니라 Windows에서 실행한 PowerShell 7.6.5를 시험했습니다. 자식 PowerShell 프로세스를 외부 실행 파일로 호출해 종료 코드 7과 0을 돌려받았습니다. 실제 백업·설치·배포 명령은 실행하지 않았습니다. 7은 이 실습의 실패 값이며 모든 도구가 같은 의미로 사용하는 값은 아닙니다.
실패·로그·다음 실행을 순서대로 비교합니다
아래 코드를 verify-native-exit-status.ps1로 저장하고 새 PowerShell 7 창에서 저장 폴더로 이동한 뒤 .\verify-native-exit-status.ps1로 실행합니다. 실행 정책으로 차단되면 정책을 낮추거나 우회하지 말고 중단하세요. 코드는 현재 PowerShell 실행 파일로 별도 프로세스를 시작하며 파일 삭제·네트워크·사용자 설정 저장은 하지 않습니다. 오류 처리 설정은 실습 스크립트 범위에만 둡니다. 작업 중인 자동화에 코드를 그대로 붙이지 않습니다.
첫 실행의 $?를 먼저 저장한 다음 종료 코드를 저장합니다. 로그 뒤에는 $?가 True지만 종료 코드는 아직 7입니다. 다음 자식 프로세스가 0으로 끝나면 $LASTEXITCODE도 0이 됩니다. savedCode에 보관한 7은 이 두 변화와 분리되어 남습니다. 한 변수로 전체 실행 이력을 판단하지 않도록 각 도구의 종료 코드를 따로 보관합니다.
같은 세션에서 바뀌는 상태값
- 자식 종료 7즉시 실패 확인
저장한 $?는 False, savedCode는 7입니다.
- 로그 출력 후마지막 명령 성공
$?는 True로 바뀌고 LASTEXITCODE는 7로 남습니다.
- 다음 자식 종료 0외부 코드도 갱신
LASTEXITCODE는 0, savedCode는 여전히 7입니다.
직접 실행한 가상 종료 코드 실습의 시간 순서입니다. 실제 설치나 백업 결과를 나타내는 화면이 아닙니다.근거: PowerShell 7.6.5 실습 결과
종료 상태 변화와 오류 처리 재현
# Run in a new PowerShell 7 session. Only child processes are started.
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false
$probe = (Get-Process -Id $PID).Path
& $probe -NoProfile -Command 'exit 7'
$immediate = $?
$savedCode = $LASTEXITCODE
Write-Output 'log after child'
$afterLog = $?
$codeAfterLog = $LASTEXITCODE
& $probe -NoProfile -Command 'exit 0'
$afterNextChild = $LASTEXITCODE
if ($immediate -ne $false -or $savedCode -ne 7 -or
$afterLog -ne $true -or $codeAfterLog -ne 7 -or
$afterNextChild -ne 0) { throw 'Unexpected status sequence' }
"immediate=$immediate saved=$savedCode afterLog=$afterLog codeAfterLog=$codeAfterLog nextChild=$afterNextChild"
$caught = $false
try { & $probe -NoProfile -Command 'exit 7' } catch { $caught = $true }
$uncaughtCode = $LASTEXITCODE
if ($caught -or $uncaughtCode -ne 7) { throw 'Unexpected default catch behavior' }
"nativePreferenceFalse: caught=$caught code=$uncaughtCode"
$caught = $false
try {
& $probe -NoProfile -Command 'exit 7'
$resultCode = $LASTEXITCODE
if ($resultCode -ne 0) { throw "Probe failed: $resultCode" }
} catch { $caught = $true }
if (!$caught) { throw 'Explicit exit check did not stop' }
"explicitCheck: caught=$caught"
& {
$PSNativeCommandUseErrorActionPreference = $true
$caught = $false
try { & $probe -NoProfile -Command 'exit 7' } catch { $caught = $true }
if (!$caught) { throw 'Preference enabled did not stop' }
"nativePreferenceTrue: caught=$caught"
}
'PASS: status capture, log reset, native overwrite, catch conditions'
# A launch failure must not reuse a previous successful process's code.
& $probe -NoProfile -Command 'exit 0'
$missingProbe = Join-Path ([IO.Path]::GetTempPath()) ('missing-' + [guid]::NewGuid().ToString('N') + '.exe')
$launchCaught = $false
$capturedCode = $null
try {
& $missingProbe
$capturedCode = $LASTEXITCODE
} catch { $launchCaught = $true }
$staleCode = $LASTEXITCODE
if (!$launchCaught -or $null -ne $capturedCode -or $staleCode -ne 0) {
throw 'Unexpected launch failure behavior'
}
"launchFailure: caught=$launchCaught capturedNull=$($null -eq $capturedCode) staleCode=$staleCode"
'PASS: launch failure cannot be treated as returned exit code'
# A successful process still needs its expected result checked.
foreach ($case in @(
@{ Name='valid'; Command="'ready'; exit 0"; Expected=$true },
@{ Name='wrong-output'; Command="'incomplete'; exit 0"; Expected=$false },
@{ Name='failed'; Command="'ready'; exit 7"; Expected=$false }
)) {
$resultText = & $probe -NoProfile -Command $case.Command
$resultCode = $LASTEXITCODE
$accepted = $resultCode -eq 0 -and $resultText -ceq 'ready'
if ($accepted -ne $case.Expected) { throw 'Unexpected result validation' }
"result=$($case.Name) code=$resultCode accepted=$accepted"
}
'PASS: exit code and expected output are separate checks'
실제 출력
log after child
immediate=False saved=7 afterLog=True codeAfterLog=7 nextChild=0
nativePreferenceFalse: caught=False code=7
explicitCheck: caught=True
nativePreferenceTrue: caught=True
PASS: status capture, log reset, native overwrite, catch conditions
launchFailure: caught=True capturedNull=True staleCode=0
PASS: launch failure cannot be treated as returned exit code
result=valid code=0 accepted=True
result=wrong-output code=0 accepted=False
result=failed code=7 accepted=False
PASS: exit code and expected output are separate checkstry/catch가 잡는 조건도 확인합니다
실습은 $PSNativeCommandUseErrorActionPreference를 false, $ErrorActionPreference를 Stop으로 두고 시작합니다. 이 조건에서는 자식 프로세스의 종료 코드 7만으로 catch에 들어가지 않았습니다. 다음 시험에서는 실행 직후 종료 코드를 확인하고 0이 아니면 throw하여 catch 진입을 확인했습니다.
오류 처리 설정 비교의 마지막 시험은 별도 스크립트 블록에서 PSNativeCommandUseErrorActionPreference를 true로 둡니다. 이때는 Stop 설정과 결합되어 7 반환을 catch가 잡았습니다. 이 결과를 근거로 기존 스크립트의 전역 설정을 일괄 변경하지 마세요. Microsoft 문서는 일부 도구가 오류 외의 정보를 0이 아닌 코드로 나타낸다고 설명합니다. 실제 도구 문서의 성공·변경 없음·부분 성공·실패 구분을 먼저 확인해야 합니다.
저장한 코드와 결과물을 함께 판정합니다
실습처럼 0만 성공인 명령은 실행, 종료 코드 저장, 실패 분기, 결과물 확인, 완료 로그의 순서로 구성합니다. 코드 0이어도 필요한 파일·항목이 없을 수 있으므로 과업별 결과 확인을 생략하지 않습니다. WinGet 목록이라면 JSON을 읽을 수 있는지와 필요한 앱 식별자가 들어 있는지를 따로 대조합니다.
반대로 PowerShell cmdlet 오류를 이전 외부 프로그램의 LASTEXITCODE로 판정하면 엉뚱한 숫자를 읽을 수 있습니다. cmdlet과 외부 실행 파일을 구분하고, 프로그램을 아예 시작하지 못한 오류도 정상적인 반환값과 구분하세요. 이 실습은 여러 외부 프로그램을 한 파이프라인으로 묶은 경우, 비동기 실행, Windows PowerShell 5.1을 검증하지 않았습니다. 그런 호출로 확장할 때는 각 프로세스의 종료 상태를 별도로 확인해야 합니다.
실행 파일이 없는 경우도 실습했습니다. 종료 코드 0을 먼저 만든 뒤 존재하지 않는 임시 경로를 호출하자 catch가 실행됐고, 그 뒤의 종료 코드 저장 줄에는 도달하지 않았습니다. 이전 LASTEXITCODE는 여전히 0이었습니다. 따라서 catch 뒤에서 그 0을 현재 명령의 성공으로 읽으면 안 됩니다. 실행 전 결과 변수를 null로 초기화하고 시작 실패를 처리한 경우에는 성공 로그나 다음 작업으로 진행하지 않습니다.
코드 마지막의 세 입력은 종료 코드 0과 정확한 ready 출력이 모두 필요한 가상 규약입니다. ready/0만 통과하고 incomplete/0과 ready/7은 거절됐습니다. 실제 프로그램에서는 ready 비교를 해당 도구의 문서화된 결과 검사로 바꿉니다. 사람이 읽는 로그 문자열을 안정적인 데이터 형식이라고 가정하지 마세요.
