将"是"或"否"转换为布尔值

wes*_*led 3 powershell boolean boolean-expression

我想解析.CSV文件中包含的用户值.我不希望我的用户输入"是"或"否",而是输入"True"或"False".在每种情况下,我想转换为等效的布尔值:$true$false.理想情况下,我想要一个默认值,所以如果有错误拼写"是或"否"我将返回我的默认值:$true$false.

因此,我想知道除了这样做之外是否还有一种巧妙的方法

if(){} else (){}
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 6

一种方式是switch声明:

$bool = switch ($string) {
  'yes' { $true }
  'no'  { $false }
}
Run Code Online (Sandbox Code Playgroud)

default如果要处理既不是"是"也不是"否"的值,请添加子句:

$bool = switch ($string) {
  'yes'   { $true }
  'no'    { $false }
  default { 'neither yes nor no' }
}
Run Code Online (Sandbox Code Playgroud)

另一种选择可能是简单的比较:

$string -eq 'yes'            # matches just "yes"
Run Code Online (Sandbox Code Playgroud)

要么

$string -match '^y(es)?$'    # matches "y" or "yes"
Run Code Online (Sandbox Code Playgroud)

这些表达式将评估$true字符串是否匹配,否则为$false.


Eri*_*ris 5

啊,powershell函数的魔力,并调用表达式.

function Yes { $true }
function No { $false }

$magicBool = & $answer 
Run Code Online (Sandbox Code Playgroud)

注意:这不区分大小写,但不会处理拼写错误