Windows PowerShell에서 스크립트를 종료하는 방법

  1. Windows PowerShell에서 스크립트를 종료하는데 Exit 명령 사용하기
  2. Windows PowerShell에서 스크립트를 종료하는데 Throw 명령 사용하기
  3. Return 명령
  4. break 명령
  5. continue 명령
Windows PowerShell에서 스크립트를 종료하는 방법

Windows PowerShell에서 스크립트를 종료하는 방법은 여러 가지가 있습니다. 그러나 이들 중 일부는 맥락상 비슷하게 들릴 수 있지만 기능 측면에서 실제 목적은 서로 다릅니다.

이 기사에서는 Windows PowerShell에서 스크립트를 종료하는 방법을 열거하고, 하나씩 정의할 것입니다.

Windows PowerShell에서 스크립트를 종료하는데 Exit 명령 사용하기

Exit 명령은 이름에서 유추할 수 있듯이 스크립트를 종료합니다. 열린 세션이 없는 경우 이 명령은 쉘이나 스크립팅 창도 닫습니다. Exit 명령은 종료 코드를 사용하여 피드백을 제공하는 데에도 유용합니다.

exit

exit 명령만 실행하면 0(기본값)이라는 종료 코드를 가질 수 있는데, 이는 성공 또는 정상 종료를 의미하며, 1은 실패 또는 포착되지 않은 예외를 의미합니다.

종료 코드의 장점은 종료 코드가 완전히 사용자 정의 가능하다는 것입니다. 종료 코드가 정수인 한 유효합니다. 또한 마지막 종료 코드를 알기 위해서는 변수 $LASTEXITCODE를 출력할 수 있습니다.

Exit.ps1

Write-Output 'Running sample script.'
exit 200

예시 코드:

PS C:\>powershell.exe .\Exit.ps1
PS C:\>Running sample script.
PS C:\>Write-Output $LASTEXITCODE
PS C:\>200

또한 실행 중인 PowerShell 스크립트에서 exit 명령을 사용하여 다른 PowerShell 파일을 호출할 때 실행 중인 스크립트도 종료된다는 점을 기억하세요.

Windows PowerShell에서 스크립트를 종료하는데 Throw 명령 사용하기

Throw 명령은 종료 코드가 있는 Exit 명령과 유사하지만 훨씬 더 많은 정보를 제공합니다. 이 명령과 사용자 정의 표현식을 사용하여 종료 오류를 생성할 수 있습니다. 일반적으로 Throw 명령은 Try-Catch 표현식의 Catch 블록 안에서 예외를 적절하게 설명하는 데 사용됩니다.

예시 코드:

Try {
    $divideAnswer = 1 / 0
}
Catch {
    Throw "The mathematical expression has a syntax error"
}

출력:

The mathematical expression has a syntax error
At line:4 char:5
+     Throw "The mathematical expression has a syntax error"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (The mathematica... a syntax error:String) [], RuntimeException
    + FullyQualifiedErrorId : The mathematical expression has a syntax error

Return 명령

Exit 명령과 달리 Return 명령은 이전 호출 지점으로 돌아가며 스크립팅 창을 닫지 않습니다.

일반적으로 스크립트 내에서 실행된 함수로부터 값을 반환하기 위해 Return 명령을 사용합니다.

예시 코드:

Function sumValues($int1, $int2) {
    Return ($int1 + $int2)
}

# The function sumValues is called below, and the script will return to 
# the same line with a value and store it in the output variable
$output = sumValues 1 2 

Write-Output $output

출력:

3

break 명령

우리는 break 명령을 사용하여 루프와 경우를 종료합니다.

예시 코드:

$numList = 1, 2, 3, 4, 5, 6, 7, 8

foreach ($number in $numList) {
    if ($number -eq 8) {
        #Terminate loop if number variable is equal to 8
        break
    }

    Write-Output $number
}

출력:

1
2
3
4
5
6
7

중첩 루프가 있는 경우, break 명령이 호출된 루프에서만 종료합니다.

예시 코드:

While ($true) {
    While ($true) {
        #The break command will only break out of this while loop
        break
    }
    #The script will continue to run on this line after breaking out of the inner while loop
}

특정 중첩 루프에서 종료하고 싶다면, break 명령은 레이블을 매개변수로 사용합니다.

While ($true) {
    :thisLoop While ($true) {
        While ($true) {
            #The break command below will break out of the `thisLoop` while loop.
            Break thisLoop
        }
    }
}

continue 명령

continue 명령은 루프 수준에서 스크립트를 종료합니다. 그러나 전체 루프를 즉시 종료하는 대신, continue 명령은 현재 반복만 종료하고 모든 반복이 처리될 때까지 루프를 계속 진행합니다.

이를 통해 루프를 실행할 때 무언가를 건너뛰기 위한 명령이라고 할 수 있습니다.

예시 코드:

$numList = 1, 2, 3, 4, 5, 6, 7, 8

foreach ($number in $numList) {
    if ($number -eq 2) {
        #The continue command below will skip number 2 and will directly process the next iteration, resetting the process to the top of the loop.
        continue
    }

    Write-Output $number
}

출력:

1
3
4
5
6
7
8
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

관련 문장 - PowerShell Script