2014-10-17 26 views
0

我已經讀過不同的來源,SWITCH語句比多個IF語句產生更好的性能。我有以下幾條具有並行條件的IF語句塊。是否可以在SWITCH塊中執行此操作?如何在switch語句中測試並行條件?

if (($statusCode -eq "OK:") -and ($messageOutput)) { 

    $returnValue = 0 
    return $returnValue 
} 

if (($statusCode -eq "WARNING:") -and ($messageOutput)) { 

    $returnValue = 1 
    return $returnValue 
} 

由於提前,

+0

-1,一個小小的研究會回答你的問題。 http://technet.microsoft.com/en-us/library/ff730937.aspx – Raf 2014-10-17 10:23:10

+0

@Raf - 不確定該鏈接是否解決了這個問題。這不是要編寫switch語句,而是涉及使用具有多個條件的交換機。 – arco444 2014-10-17 10:30:14

+0

如果你真的在尋找多種條件,我認爲你可以做'switch($ true)' – Matt 2014-10-17 10:51:23

回答

1

您在這裏有一個常量,其爲$messageOutput,這樣的環境實在不平行。你可以這樣做:

if($messageOutput) { 
    switch ($statusCode) { 
    "OK:" { 0 } 
    "WARNING:" { 1 } 
    default { 1 } 
    } 
} 

因爲你不需要重新檢查每個變量對每個條件這樣會更有效。

+0

謝謝arco444。好的改進。我將運行性能基準。 – 2014-10-17 13:49:08

0

對於這種特殊情況,Arco444有最好的答案。但值得注意的是,switch區塊中可能有多個條件。在另一種情況下,SO用戶在這裏找到自己的方式:

Switch($true){ 
    (($statusCode -eq "OK:") -and ($messageOutput)){"Alright"} 
    (($statusCode -eq "WARNING:") -and ($messageOutput)){"Not Alright"} 
    default{"Something Wrong"} 
} 

的條件都evalutaed基礎上,如果是$true。如果沒有其他條件爲真,default會被捕獲。

0

這裏有接近多個條件與交換機的一種方法:

Switch ([string][int[]]($Condition1,$Condition2)) 
{ 
    '1 1' { 'Both conditions are true' } 
    '1 0' { 'Condition1 is true and Condition2 is false' } 
    '0 1' { 'Condition1 is false and Condition2 is true' } 
    '0 0' { 'Both conditions are false' } 
} 
+0

我將不得不嘗試這個。謝謝。 – 2014-10-17 13:51:38