Powershell:如何将 bool 值传递给函数参数?

标签 powershell

我在 Powershell 中创建了一个函数,并希望将参数 -Foo 作为 bool 值传递。

我已经简化了我的可视化用例:

function Get-Foobar {

    [CmdletBinding()]
    param (
        [bool]$Foo
    )

    if ($Foo) {
        Write-Host "Foo!"
    }
    else {
        Write-Host "Bar!"
    }
}

当我调用函数 Get-Foobar -Foo $true 时,该函数按预期工作。但这不是我想要的。只需 Get-Foobar -Foo 就足够了。

Referring to the documentation ,在调用函数时指定参数应该已经返回 true。但显然这不起作用。

最佳答案

您正在寻找开关参数:

Switch parameters are parameters with no parameter value. Source.

例子:

Param(
    [Parameter(Mandatory=$false)]
    [Switch]
    $Foo
)

关于Powershell:如何将 bool 值传递给函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68435864/

相关文章:

windows - 在 powershell 2 中仅返回带有 Get-childitem 的文件

powershell - 如何复制特定文件并将其粘贴到其他位置保存结构?

powershell - 在 Windows 10 上通过 ssh 在 cygwin 上获得 rsync 的神奇组合

powershell - PowerShell GraphQL突变解析错误

linux - 是否有适用于 Windows 和 Linux 的 vscode 片段路径变量?

xml - 无法使用 powershell 提取 XML 节点的值

windows - 如何更改 powershell 中的单个语法着色?

powershell - Import-PSSession-内存泄漏

web-services - 使用PowerShell代码访问_vti_bin/lists.asmx

powershell - PowerShell变量 `${$}`, `${^}`和 `$?`