PowerShell スクリプトは If ステートメントの実行後に停止します

PowerShell スクリプトは If ステートメントの実行後に停止します

困惑しています。開発中に、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

write-host と write-output も試しましたが、どちらも成功しませんでした。コンソールからの出力は次のとおりです。

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 コマンドが含まれている場合、シェルに戻ったときに実行するコマンドはもうないため、このように使用される Return は基本的に Exit と同じになります。

それで、'if'と'else'からreturn文を削除する必要があります変数のみを残してその内容を表示します。

例:

    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
}

関連情報