[英]What's the best way to make a recursive call with a SWITCH parameter?
In the below example I've got an IF
statement to determine which parameters send to Demo
when called recursively. 在下面的示例中,我有一个
IF
语句来确定递归调用时将哪些参数发送给Demo
。 If $y
were a boolean value rather than a switch I could simply call Demo -x $x -y $y
; 如果
$y
是一个布尔值而不是一个开关,我可以简单地称为Demo -x $x -y $y
; but as a switch that's not a viable option. 但是作为一个开关,这不是一个可行的选择。
function Demo {
[CmdletBinding()]
param (
[int]$x
,[switch]$y
)
process {
$x--
if ($x -gt 0) {
"$x - $($y.IsPresent)"
if($y.IsPresent) {
Demo -x $x -y
} else {
Demo -x $x
}
}
}
}
Demo 10 -y
Demo 10
Question 题
Is the above the correct way to handle this scenario, or does a cleaner option exist? 以上是处理这种情况的正确方法,还是存在更清洁的选项?
You can force a switch parameter by calling it like this: -Switch:$true
(obviously redundant in most cases) or -Switch:$false
so for your example: 您可以通过这样调用它来强制使用switch参数:
-Switch:$true
(在大多数情况下显然是多余的)或-Switch:$false
因此对于您的示例:
Demo -y:$y
By the way in this example, you could also just use splatting: 顺便说一下,在本示例中,您还可以使用splatting:
Demo @PSBoundParameters
But your post is clearly a MVCE so this may not apply to what you're actually doing, or may need modification, especially if you have default values for some parameters (full disclosure: my blog). 但是您的帖子显然是MVCE,因此这可能不适用于您的实际工作,或者可能需要修改,特别是如果您对某些参数具有默认值 (完整披露:我的博客)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.