检查开关值的正确方法是什么?
function testSwitch
{
Param(
[switch] $swth
)
Write-Host "Value of swth is $swth"
if($swth.IsPresent){
Write-host "Switch is present"
}
if($swth){
Write-Host "Switch is present"
}
}
testSwitch -swth
我都知道语句是否正常,但是如何?
答案 0 :(得分:5)
$swth.IsPresent
和$swth
可以可互换地使用 ,因为在布尔上下文中(例如if
有条件){ {1}}(代表[switch]
的类型switch parameter的实例)有效地返回$swth
属性的值。 [1]
实际上, .IsPresent
可能更可取 [2] ,不仅是为了简洁,而且因为$swth
属性的命名有些混乱:
.IsPresent
本身并不表示开关的存在,而是指示其值是否为.IsPresent
。
虽然单独指定一个开关-$true
-表示两者都是 ,但如果您将其明确设置为-swth
,则情况并非如此:传递$false
即使切换明显存在,也会使-swth:$false
返回.IsPresent
。
显式传递$false
并不常见,但是有其用途,例如在选择$false
退出确认提示时。
因此,如果要区分用户未通过开关和用户通过值为-Confirm:$false
的开关,{{1 }}对您没有帮助-您必须使用$false
[1]在转换为布尔值时(发生在方法LanguagePrimitives.IsTrue()
中),PowerShell调用.IsPresent
实例的.ToBool()
method,而该实例又返回{ {1}}属性。
[2]唯一需要注意的是,您必须意识到$PSBoundParameters.ContainsKey('swth')
不是布尔值([switch]
),而是类型.IsPresent
,这在其他情况下可能很重要上下文。
答案 1 :(得分:0)
仅使用if
/ else
子句会更简单:
Function Get-FruitDetails {
[CmdLetBinding()]
Param (
[String]$Fruit,
[Switch]$Yellow
)
Write-Verbose "Get fruit details of $Fruit"
$Result = [PSCustomObject]@{
Fruit = $Fruit
Yellow = $null
}
if ($Yellow) {
Write-Verbose 'Color is yellow'
$Result.Yellow = $true
}
else {
Write-Verbose 'Color is not yellow'
$Result.Yellow = $false
}
$Result
}
Get-FruitDetails -Fruit 'Banana' -Yellow -Verbose
Get-FruitDetails -Fruit 'Kiwi' -Verbose
这将输出以下内容:
Fruit Yellow
----- ------
Banana True
Kiwi False
一些提示:
Write-Host
,这是为了控制台程序。如果您想查看消息,最好使用Write-Verbose
并添加-Verbose
开关Get-Verb
轻松找到。其他人可以更轻松地查看您的函数Get
,Set
,Remove
,...