2017-07-27 74 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