programing

호출 연산자를 사용하여 종료 코드가 0이 아닌 경우 PowerShell 스크립트가 종료되지 않는 이유는 무엇입니까?

iphone6s 2023. 8. 20. 10:32
반응형

호출 연산자를 사용하여 종료 코드가 0이 아닌 경우 PowerShell 스크립트가 종료되지 않는 이유는 무엇입니까?

호출 연산자를 사용할 때 종료 코드가 0이 아닌 경우 PowerShell 스크립트가 종료되지 않는 이유는 무엇입니까?$ErrorActionPerference = "Stop"?

다음 예제를 사용하여 결과를 얻습니다.managed to get here with exit code 1:

$ErrorActionPreference = "Stop"

& cmd.exe /c "exit 1"

Write-Host "managed to get here with exit code $LASTEXITCODE"

호출 연산자에 대한 Microsoft 설명서에서는 호출 연산자를 사용할 때 수행해야 하는 작업에 대해 설명하지 않고 다음 사항만 설명합니다.

명령, 스크립트 또는 스크립트 블록을 실행합니다.호출 연산자("호출 연산자"라고도 함)를 사용하여 변수에 저장되고 문자열로 표시되는 명령을 실행할 수 있습니다.호출 연산자는 명령을 구문 분석하지 않으므로 명령 매개 변수를 해석할 수 없습니다.


또한 예상되는 동작인 경우 통화 교환원이 오류를 계속 발생시키는 것이 아니라 오류를 발생시키는 것이 있는 다른 방법이 있습니까?

반환 코드는 PowerShell 오류가 아닙니다. 다른 변수와 동일한 방식으로 확인됩니다.

그런 다음 변수에 대한 작업을 수행해야 합니다.throw종료 오류로 보기 위해 PowerShell을 스크립트에 사용하는 오류:

$ErrorActionPreference = "Stop"

& cmd.exe /c "exit 1"

if ($LASTEXITCODE -ne 0) { throw "Exit code is $LASTEXITCODE" }

거의 모든 PowerShell 스크립트에서 저는 "빠른 실패"를 선호하기 때문에 거의 항상 다음과 같은 작은 기능을 사용합니다.

function Invoke-NativeCommand() {
    # A handy way to run a command, and automatically throw an error if the
    # exit code is non-zero.

    if ($args.Count -eq 0) {
        throw "Must supply some arguments."
    }

    $command = $args[0]
    $commandArgs = @()
    if ($args.Count -gt 1) {
        $commandArgs = $args[1..($args.Count - 1)]
    }

    & $command $commandArgs
    $result = $LASTEXITCODE

    if ($result -ne 0) {
        throw "$command $commandArgs exited with code $result."
    }
}

예를 들어 이렇게 하겠습니다.

Invoke-NativeCommand cmd.exe /c "exit 1"

그러면 다음과 같은 PowerShell 오류가 발생합니다.

cmd /c exit 1 exited with code 1.
At line:16 char:9
+         throw "$command $commandArgs exited with code $result."
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (cmd /c exit 1 exited with code 1.:String) [], RuntimeException
    + FullyQualifiedErrorId : cmd /c exit 1 exited with code 1.

명령이 실패한 경우 동일한 코드 행에 오류를 발생시킬 수 있습니다.

& cmd.exe /c "exit 1"; if(!$?) { throw }

자동 변수:$?

언급URL : https://stackoverflow.com/questions/47032005/why-does-a-powershell-script-not-end-when-there-is-a-non-zero-exit-code-using-th

반응형