Does Select-Object -First terminate native executable processes in the pipeline?
0 reputation · 15 Nov 2021, 08:00 UTC
0 reputation · 15 Nov 2021, 08:00 UTC
In PowerShell, Select-Object -First N is documented to stop the upstream pipeline once the specified number of objects is received. This mechanism prevents upstream cmdlets from running to completion, which is critical for performance when handling large datasets.
However, there is uncertainty regarding how this early termination behaves when the upstream source is a native executable rather than a PowerShell cmdlet. While a cmdlet may stop emitting objects, a native process writing to stdout may behave differently depending on the PowerShell edition and how the pipe is handled by the underlying host.
Which behavior is expected when piping a long-running native command into Select-Object -First? Does the native process receive a signal to terminate, or does it continue running until completion despite the pipeline being closed by the downstream cmdlet?
34775 reputation · 15 Nov 2021, 17:45 UTC
Select-Object -First does not send a termination signal to the upstream process. It stops reading from the pipeline after receiving the requested number of objects, which closes its read end of the pipe.
If the native executable checks the result of each write and exits when the write fails, it will terminate shortly after Select-Object -First satisfies its request. If it ignores write errors or buffers output, it may continue running until it attempts to write more data and encounters the error.
. estprogram.exe | Select-Object -First 2 and observe whether the process exits after two lines (you can check with Get-Process or the program’s exit code).To give a definitive recommendation, we need to know whether the native executable you are piping checks the success of its write operations and terminates on failure. If it does, the process will likely stop early; if it does not, it may continue until it attempts further output.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.