簡體   English   中英

Powershell:對腳本塊使用潑濺?

[英]Powershell: using splatting with scriptblocks?

我寫了一個簡單的 function 從一個 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 看起來像這樣:

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 時,如何存儲該值以便執行它?

您需要先評估參數值,然后再將它們粘貼到哈希表中。 像這樣的東西。

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

這在有限的測試中對我有用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM