CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Strange Behavior with Custom Function Returning Multiple Objects

👀 Views: 25 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-29
powershell function pipeline

I'm dealing with I'm trying to configure I've hit a wall trying to I'm experiencing an scenario with a custom PowerShell function that is supposed to return multiple objects, but it seems to be returning only the last object when called in a pipeline... Here's the function I'm working with: ```powershell function Get-CustomObjects { $objects = @() for ($i = 1; $i -le 5; $i++) { $obj = New-Object PSObject -Property @{ Id = $i; Name = "Object$i" } $objects += $obj } return $objects } ``` When I call the function in a pipeline like this: ```powershell Get-CustomObjects | ForEach-Object { $_.Name } ``` I only get `Object5` as the output. However, if I run the function directly using `Get-CustomObjects` (without piping), it returns all objects as expected: ```powershell Get-CustomObjects ``` This returns: ``` Id Name -- ---- 1 Object1 2 Object2 3 Object3 4 Object4 5 Object5 ``` I've tried modifying the function to use `Write-Output` instead of `return`, but that didn't change the behavior either: ```powershell function Get-CustomObjects { for ($i = 1; $i -le 5; $i++) { $obj = New-Object PSObject -Property @{ Id = $i; Name = "Object$i" } Write-Output $obj } } ``` Still, the scenario continues. I've also checked the `$PSVersionTable.PSVersion` to ensure I'm indeed using PowerShell 7.3. Is there something I'm missing here? Why does the function only return the last object when piped? I'd be grateful for any help. I'm working on a application that needs to handle this. Is there a simpler solution I'm overlooking? For context: I'm using Powershell on macOS. Is there a better approach?