If 문을 실행한 후 PowerShell 스크립트가 중지됩니다.

If 문을 실행한 후 PowerShell 스크립트가 중지됩니다.

나는 당황했다. 개발하는 동안 2012 R2 상자에서 아래 코드를 실행하고 있습니다. 이 부분이 수행하는 작업은 호스트 이름을 가져오고 끝에서 숫자를 가져와 함수를 실행하여 홀수인지 짝수인지 확인한 다음 이를 기반으로 저장 위치를 ​​설정하는 것입니다.

If 문이 값을 반환한 후 어떤 이유로 스크립트가 종료된 것처럼 스크립트 실행이 중지됩니다. 보시다시피 write-debug "message 3"을 추가했는데 단순히 등록조차 되지 않습니다. 이와 같은 시나리오에 대한 PS 문제점을 아는 사람이 있습니까? 아니면 제가 어딘가에서 실수를 한 걸까요? 서버가 WMF 4.0을 실행 중입니다.

function check-oddOrEven($number)
{
    If([bool]!($number%2))
    {
       $OddEvnResult = "Even"
       return $OddEvnResult
    }
    Else
    {
       $OddEvnResult = "Odd"
       return $OddEvnResult
    }
}

Write-Debug "message1" -debug

$oddStrgPath = "C:\ClusterStorage\Volume1"
$evnStrgPath = "C:\ClusterStorage\Volume2"

$hostname = $env:computername
#$hostname = "testN02"
$OddEvnSplit = $hostname.split('N')[1]

Write-Debug "message2" -debug

$OddEvnResult = check-oddOrEven $OddEvnSplit
if ($OddEvnResult -eq "Odd")
{
    write-host "Odd number in hostname detected (1,3,5..etc). Setting storage path to" $oddStrgPath
    #set-vmhost -VirtualHardDiskPath $oddStrgPath -VirtualMachinePath $oddStrgPath
    $OEresult= $oddStrgPath
    return $OEresult
}
else
{
    write-host "Even number in hostname detected (2,4,6..etc). Setting storage path to" $evnStrgPath
    #set-vmhost -VirtualHardDiskPath $evnStrgPath -VirtualMachinePath $oddStrgPath
    $OEresult= $evnStrgPath
    return $OEresult
}

Write-Debug "message3" -debug

나는 쓰기 호스트와 쓰기 출력을 시도했지만 성공하지 못했습니다. 콘솔의 출력은 다음과 같습니다.

DEBUG: message1
DEBUG: message2
Even number in hostname detected (1,3,5..etc). Setting storage path to C:\ClusterStorage\Volume2
C:\ClusterStorage\Volume2

답변1

읽어주세요StackOverflow의 이 게시물'반환'문에 대해. 요약은 다음과 같습니다.

반품: 이렇게 됩니다이전 호출 지점으로 돌아갑니다. 스크립트(함수 외부)에서 이 명령을 호출하면 셸로 돌아갑니다. 셸에서 이 명령을 호출하면 셸로 돌아갑니다(이는 셸에서 실행된 단일 명령에 대한 이전 호출 지점입니다).. 함수에서 이 명령을 호출하면 함수가 호출된 위치로 돌아갑니다.

반환된 호출 지점 이후의 명령 실행은 해당 지점부터 계속됩니다. 스크립트가 쉘에서 호출되고 함수 외부의 Return 명령이 포함된 경우 쉘로 돌아올 때 더 이상 실행할 명령이 없으므로 이러한 방식으로 사용되는 Return은 기본적으로 Exit와 동일합니다.

그래서,'if' 및 'else'에서 반환 문을 제거해야 합니다., 내용을 표시할 변수만 남겨 둡니다.

예:

    if ($OddEvnResult -eq "Odd")
{
    write-host "Odd number in hostname detected (1,3,5..etc). Setting storage path to" $oddStrgPath
    #set-vmhost -VirtualHardDiskPath $oddStrgPath -VirtualMachinePath $oddStrgPath
    $OEresult= $oddStrgPath
    $OEresult
}
else
{
    write-host "Even number in hostname detected (2,4,6..etc). Setting storage path to" $evnStrgPath
    #set-vmhost -VirtualHardDiskPath $evnStrgPath -VirtualMachinePath $oddStrgPath
    $OEresult= $evnStrgPath
    $OEresult
}

관련 정보