2017-07-27 34 views
0
$q = 0 
do { 
    $a = write-input "enter value" 

    switch ($a) { 
     1.{ some option } 
     2.{} 
     default {} 
    } 
} while ($a -gt $q) 

空字符在上面的代碼中,如果我們給$a=$null值然後切換從while循環終止。請幫我跳過空檢查並繼續循環。避免的powershell

+1

'$一個-gt $ q' - >'$一個-eq $空 - 或$一個-gt $ q' –

+0

如果使用$ a -eq $ null,我將終止在循環之外...循環不應該終止爲空值讀取 – Pradeep

+1

然後在第一個$ a的值不是$ null地點。它是一個空字符串嗎?如果這樣''不是$ a或$ a -gt $ q'可能工作。 「write-input」究竟做什麼/返回?沒有該名稱的標準cmdlet。 –

回答

0

正如Ansgar Wiechers在評論中指出的,比較$null -gt 0False。這會終止您的While循環。你可以更新您的while聲明while ($a -eq $null -or $a -gt $q)

另一種方法是使用遞歸函數,

function Example-Function { 
    switch (Read-Host "Enter Value") { 
     1 { "Option 1"; Example-Function } 
     2 { "Option 2"; Example-Function } 
     default { "Invalid Option, Exiting" } 
    } 
} 
+0

很好地使用PS中的遞歸。我第一次看到它的有效用例。 OP可能希望擴展正在列出的選項,例如''選項:'r'nOpt 1:thing「'在切換之前 – TheIncorrigible1