Skip to content

Out-Null is not expensive to pipe to #8333

@powercode

Description

@powercode

This was fixed quite a while ago.

See src\System.Management.Automation\engine\runtime\Operations\MiscOps.cs:468-475

                var cmdletInfo = commandProcessor?.CommandInfo as CmdletInfo;
                if (cmdletInfo?.ImplementingType == typeof(OutNullCommand))
                {
                    var commandsCount = pipelineProcessor.Commands.Count;
                    if (commandsCount == 1)
                    {
                        // Out-Null is the only command, bail without running anything
                        return;
                    }

                    // Out-Null is the last command, rewrite command before Out-Null to a null pipe, but
                    // only if it didn't redirect anything, e.g. `Get-Stuff > o.txt | Out-Null`
                    var nextToLastCommand = pipelineProcessor.Commands[commandsCount - 2];
                    if (!nextToLastCommand.CommandRuntime.OutputPipe.IsRedirected)
                    {
                        pipelineProcessor.Commands.RemoveAt(commandsCount - 1);
                        commandProcessor = nextToLastCommand;
                        nextToLastCommand.CommandRuntime.OutputPipe = new Pipe { NullPipe = true };
                    }
                }

A null pipe is created if piped to out-null. It is roughly 10% slower than assigning to $null, but in most cases not even noticeable.

PS > measure-command { 1..1000000 | foreach{$_} | out-null} | ft
Days Hours Minutes Seconds Milliseconds
---- ----- ------- ------- ------------
0    0     0       3       701
PS > measure-command { $null = 1..1000000 | foreach{$_}} | ft
Days Hours Minutes Seconds Milliseconds
---- ----- ------- ------- ------------
0    0     0       3       51

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions