【发布时间】:2011-03-19 02:15:51
【问题描述】:
在尝试使用脚本块时,我尝试将脚本块参数与高级功能一起使用,并注意到它的执行方式与提供给已编译 cmdlet 时不同。
在查看 PowerShell 团队博客中的 this blog post 时,如果脚本块不是参数的有效输入,PowerShell 引擎似乎应该评估脚本块。似乎在调用带有 scriptblock 参数的函数时,它会尝试将 scriptblock 直接转换为参数类型,而不是根据管道中的当前对象评估 scriptblock。
我的意图是复制如下行为:
Import-CSV somecsv.csv | get-wmiobject -class {$_.class} -Computer {$_.computer}
用于高级功能。
示例脚本:
$sb = {throw "If there was an error, the scriptblock was evaluated!"}
function test ()
{
param (
[Parameter()]
[string]
$ThisShouldBeEvaluatedForEachItem,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[string]
$FullName
)
process
{
write-host $Fullname, $ThisShouldBeEvaluatedForEachItem
}
}
Get-ChildItem | test -ThisShouldBeEvaluatedForEachItem $sb
这是预期的行为还是我走错了方向?
基于Keith's response,我将 ValueFromPipeline 和 ValueFromPipelineByPropertyName(在两个单独的测试中)添加到 ThisShouldBeEvaluatedForEachItem 参数的 Parameter 属性。这样做会使示例工作,尽管它似乎违背了团队博客文章中脚本块参数的规定目的。
【问题讨论】: