PowerShell 腳本在執行 If 語句後停止

PowerShell 腳本在執行 If 語句後停止

我很困惑。當我開發它時,我在 2012 R2 機器上運行以下程式碼。這一部分所做的就是取得主機名,從末尾取得數字,運行一個函數來查看它是奇數還是偶數,然後根據該值設定儲存位置。

由於某種原因,在 If 語句傳回值之後,腳本停止運行,就像腳本已經結束一樣。有人知道這樣的場景有什麼 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關於“返回”聲明。總結如下:

返回: 這會返回前一個呼叫點。如果您從腳本(在任何函數之外)呼叫此命令,它將返回 shell。如果您從 shell 呼叫此命令,它將返回到 shell(這是從 shell 運行的單一命令的前一個呼叫點)。如果您從函數呼叫此命令,它將返回到呼叫該函數的位置。

在傳回的呼叫點之後執行任何命令將從該點繼續執行。如果從 shell 呼叫一個腳本,並且它在任何函數之外包含 Return 命令,那麼當它返回到 shell 時,就不再需要執行命令,因此以這種方式使用的 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
}

相關內容