已编译的 cmdlet 和高级函数的脚本块参数评估是否不同?
在试验脚本块时,我尝试将脚本块参数与高级函数一起使用,并注意到它的执行方式与提供给已编译的 cmdlet 时的执行方式不同。
在审查 此博文来自 PowerShell 团队博客,如果脚本块不是参数的有效输入,则 PowerShell 引擎似乎应该评估脚本块。看起来,当使用脚本块参数调用该函数时,它会尝试直接将脚本块转换为参数类型,而不是根据管道中的当前对象评估脚本块。
我的目的是复制以下行为:
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
这是预期的行为还是我走错了方向?
In experimenting with scriptblocks, I was attempting to use a scriptblock parameter with an advanced function and noticed that it performs differently than when supplied to a compiled cmdlet.
In reviewing this blog post from the PowerShell Team blog, it appears that the PowerShell engine should be evaluating the scriptblock if a scriptblock is not a valid input for the parameter. It seems that when calling the function with a scriptblock parameter, it attempts to convert a scriptblock to the parameters type directly, rather than evaluating the scriptblock based on the current object in the pipeline.
My intention is to duplicate behavior like:
Import-CSV somecsv.csv | get-wmiobject -class {$_.class} -Computer {$_.computer}
for advanced functions.
Example script:
$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
Is this the intended behavior or am I headed in the wrong direction?
Based on Keith's response, I added ValueFromPipeline and ValueFromPipelineByPropertyName (in two separate tests) to the Parameter attribute for the ThisShouldBeEvaluatedForEachItem parameter. Doing that makes the example work, though it seems to defeat the stated purpose of scriptblock parameters from the Team Blog post.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果参数是
ValueFromPipeline
或ValueFromPipelineByPropertyName
,则 PowerShell 将评估 Scriptblock 并尝试将结果强制为参数类型。不久前我们从 PowerShell 团队获得了以下信息:If the parameter is
ValueFromPipeline
orValueFromPipelineByPropertyName
then PowerShell will evaluate the Scriptblock and try to coerce the result to the parameter type. We got this info from the PowerShell team a while back: