简体   繁体   中英

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. 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.

Here is my example (this would produce 3 records):

$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? 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:

ProcessFeedback -feedbackInput $audioSessions

Then, inside my function I do the filter with the Where-Object statement resulting in something like this:

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM