简体   繁体   English

用SWITCH参数进行递归调用的最佳方法是什么?

[英]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.

相关问题 什么是检查开关参数的正确方法 - What is the right way to check a switch parameter 对此进行管道传递和过滤的最佳方法是什么? - What's the best way to pipeline this and filter? PowerShell解析这些字符串的最佳方法是什么? - What's the best way in PowerShell to parse these strings? 在PowerShell中检查Web服务器上的IP地址开关有什么好方法? - What's a good way in PowerShell to check for an IP address switch on a webserver? 将值传递到运行/后台脚本块的最佳方法是什么? - What's the best way to pass values to a running/background script block? 确定当前 PowerShell 脚本位置的最佳方法是什么? - What's the best way to determine the location of the current PowerShell script? 将 DateTime 戳记作为计算属性进行比较和组合的最佳方法是什么? - What's the best way to compare and combine the DateTime stamp as calculated property? 在 PowerShell 中,将两个表合并为一个表的最佳方法是什么? - In PowerShell, what's the best way to join two tables into one? 使用 powershell 将数据发布到 Elastic Search 的最佳方式是什么? - What's the best way to post data to Elastic Search using powershell? 在WinMD文件中获取名称空间的最佳方法是什么? - What's the best way to get the namespaces in a WinMD file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM