[英]Unexpected behavior in function processing PowerShell pipeline
I created a function to process items I want from an object and sort them into a new PSCustomObject. 我创建了一个函数来处理我想要的对象项目,并将它们分类为一个新的PSCustomObject。 If I pass the object through the pipeline I get some duplicated and odd results versus passing the object as a parameter into the function and using a ForEach-Object loop.
如果我通过管道传递对象,我会得到一些重复和奇怪的结果,而不是将对象作为参数传递给函数并使用ForEach-Object循环。
Here is my example (this would produce 3 records): 这是我的例子(这会产生3条记录):
$audioSessions | Where-Object {$_.QoeReport.FeedbackReports}
Versus this (which produces six and some are duplicated: 与此相比(产生六个,一些是重复的:
$audioSessions | Where-Object {$_.QoeReport.FeedbackReports} | ProcessFeedback
Here is the difference in the output: 这是输出的差异:
Any idea why this would be happening? 知道为什么会这样吗? There are 3 objects I'm passing to the ProcessFeedback function, no?
我传递给ProcessFeedback函数有3个对象,不是吗? Why are some items duplicated and some are not?
为什么有些项目重复,有些则不重复?
If I choose to pass the entire variable into the function and loop within it, I get the 3 objects back from my function as expected: 如果我选择将整个变量传递给函数并在其中循环,我会按预期从函数中获取3个对象:
ProcessFeedback -feedbackInput $audioSessions
Then, inside my function I do the filter with the Where-Object statement resulting in something like this: 然后,在我的函数内部,我使用Where-Object语句进行过滤,得到如下内容:
function ProcessFeedback{
[cmdletbinding()]
Param(
[Parameter(mandatory=$true, valuefrompipeline=$true)]
$feedbackInput
)
begin{}
process{
$feedbackInput | Where-Object {$_.QoeReport.FeedbackReports} | ForEach-Object{
[array]$newObject += [PSCustomObject][ordered]@{
FromUri = $_.FromUri
ToUri = $_.ToUri
CaptureTime = $_.QoeReport.FeedbackReports.CaptureTime
Rating = $_.QoeReport.FeedBackReports.Rating
}
}
return $newObject
}
}
NOTE: When I pass the object through the pipeline, I remove the Where-Object statement in the ProcessFeedback function as I only ever see one object passed to it at a time. 注意:当我通过管道传递对象时,我删除了ProcessFeedback函数中的Where-Object语句,因为我一次只看到一个对象传递给它。
Okay so I think I figured this out... 好的,所以我想我想出来了......
If you're passing multiple objects through the pipeline, there is no need to add the results together. 如果您通过管道传递多个对象,则无需将结果一起添加。
I simply changed the code to remove the [array]
and +=
values from $newObject
as follows: 我只是更改代码以从
$newObject
删除[array]
和+=
值,如下所示:
function ProcessFeedback{
begin{}
process{
$newObject = [PSCustomObject][ordered]@{
FromUri = $_.FromUri
ToUri = $_.ToUri
CaptureTime = $_.QoeReport.FeedbackReports.CaptureTime
Rating = $_.QoeReport.FeedBackReports.Rating
}
}
return $newObject
}
}
Then run it like this: 然后像这样运行:
[array]$arrFeedbackResults += $audioSessions | Where-Object {$_.QoeReport.FeedbackReports} | ProcessFeedback
I also removed the input parameter from the function as the object is passed through the pipeline anyway. 我还从函数中删除了输入参数,因为无论如何对象都是通过管道传递的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.