检查开关值的正确方法是什么?
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
我知道如果这两种说法都有效,但怎么做呢?
发布于 2019-09-04 00:16:15
只使用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
、.https://stackoverflow.com/questions/57783941
复制