【问题标题】:Powershell: using splatting with scriptblocks?Powershell:使用带有脚本块的飞溅?
【发布时间】:2011-07-19 05:00:06
【问题描述】:

我编写了一个简单的函数来从一个 xml 文件中创建一个哈希表,该文件将包含应该传递给 cmdlet 的参数。 我的 XML 文件如下所示:

<params>
    <Parameter>
        <Name>After</Name>
        <Value>(get-date).adddays(-7)</Value>
    </Parameter>
    <Parameter>
        <Name>Log</Name>
        <Value>System</Value>
    </Parameter>
</params>

我的函数如下所示:

function Create-ParamTable {
param ([string]$ConfigFile,[string]$Root = "params", [string]$Child = "Parameter")

$hash = @{}
[xml]$config = get-content $ConfigFile
foreach ($param in $config.$root.$child) {
    $hash.add($param.name,$param.value)
}
return $hash
}

我将返回的哈希表与 splat-operator 一起使用:

PS > $h = create-paramtable -configfile c:\tmp\params.xml ; get-eventlog @h

我希望能够将脚本块作为参数值传递,以便使用 get-date 等其他 cmdlet 来计算一些值。
例如:我想将 get-eventlog 的参数存储在 xml-config-file 中,但我总是希望拥有过去 7 天的日志。

当通过 splatting 将值传递给 cmdlet 时,我如何存储该值以使其执行?

【问题讨论】:

    标签: scripting powershell


    【解决方案1】:

    您需要先评估参数值,然后再将它们粘贴到哈希表中。像这样。

    foreach ($param in $config.$root.$child) {
        $hash.add($param.name,(Invoke-Expression $param.value))
    }
    

    【讨论】:

      【解决方案2】:

      这在有限的测试中对我有用:

       $hash.add($($param.name),$($param.value))
      

      【讨论】:

        猜你喜欢
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        • 2022-08-10
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-01-04
        相关资源
        最近更新 更多