Dynamic 如何在Powershell中传递动态参数?

Dynamic 如何在Powershell中传递动态参数?,dynamic,powershell,parameters,Dynamic,Powershell,Parameters,我想用动态参数调用现有的commandlet 因此,我不想这样做(以write host为例),而是希望以一种智能的方式来做 # these are the dynamic parameters which maybe get passed into my function or script # they would be $null be default of course $forecolor = 'Green' $newline = $true # now build the "dyn

我想用动态参数调用现有的commandlet

因此,我不想这样做(以write host为例),而是希望以一种智能的方式来做

# these are the dynamic parameters which maybe get passed into my function or script
# they would be $null be default of course
$forecolor = 'Green'
$newline = $true

# now build the "dynamic" write-host...
if ($forecolor) {
    if ($newline) {
        write-host -fore $forecolor "Hello world"
    }
    else {
        write-host -fore $forecolor "Hello world" -nonewline
    }
}
else {
    if ($newline) {
        write-host "Hello world"
    }
    else {
        write-host "Hello world" -nonewline
    }
}
这当然很难看。帮我把它弄漂亮点


我已经试过设置
$forecolor='-fore Green'
,它只输出“-fore Green Hello world”。我可以考虑将参数列表传递给函数,并为列表中的每个参数添加相应的参数-我只是不知道如何保存参数。

您可以将变量作为参数传递给
Write Host

Write-Host -Fore $forecolor -NoNewLine:(!$newline) 'Hello World'
要实现真正的动态方式,您可以使用哈希表:

$params = @{ NoNewLine = $true; ForegroundColor = 'Green' }
然后使用splat操作符

Write-Host @params Hello World

在以这种方式调用
Write Host
之前,您可以将参数及其值添加到哈希表中。

您看过参数集了吗?大卫,这些对这里有什么帮助?我很困惑,太棒了!这里有一篇关于挥霍的文章:以前从未听说过这种魔法。谢谢。我在PowerShell工作多年,从未听说过这件事。现在我终于做到了:很棒的功能!您的上一个示例已经暗示了这一点,但为了清楚起见,您也可以混合搭配:
Write Host@params Hello World-BackgroundColor White