4

If you open up a command prompt and type this:

echo foobar > nul 

it will print nothing, since nul swallows all of its input. But if you run the command with PowerShell:

powershell "echo foobar" > nul 

it will output foobar to the console. Why is this, and what can I do to fix it?

edit: Here is the output of $PSVersionTable. It looks like I'm using PowerShell v5.0.

4
  • Works fine in the command-prompt for me in version 3.0. Commented Feb 21, 2016 at 21:57
  • What version of Powershell are you using? I ran your example from a cmd prompt and it ran correctly. I did not get any output. I am using version 4.0. Commented Feb 21, 2016 at 21:58
  • @rrirower According to $PSVersionTable.PSVersion, it looks like I'm using 5.0. Commented Feb 21, 2016 at 22:03
  • Can't reproduce: Server 2012 x64/PS 5.0 Preview (5.0.10018.0). Commented Feb 22, 2016 at 20:35

1 Answer 1

5

Note: I'm assuming you're invoking your command from cmd.exe, not from within PowerShell, which is consistent with the symptoms I'm seeing.

Methinks you've stumbled upon a bug in PS (PowerShell) v5 (not present in v3; comments on the question suggest it's also not in v4), though I don't fully understand why PS is to blame, because I'd expect cmd.exe to handle the redirection.
I may be missing something, however, so do let me know.

PowerShell should send its so-called success stream - things output by default, including with echo, which is an alias of Write-Output - to the outside world's stdout.

In older PS versions >NUL does effectively suppresses PowerShell's output.
Curiously, the bug in v5 only affects NUL, whereas redirecting to an actual file works.

As for workarounds:

If your code is v2-compatible, try this:

powershell -version 2 "echo foobar" > NUL 

Otherwise, redirect to an actual file and delete that file afterward:

powershell "echo foobar" > "%TEMP%\NUL-bug-workaround" & del "%TEMP%\NUL-bug-workaround" 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Passing in -Version 2 seems to have solved the problem. You've just freed me after 2 hours of banging my head on this :D
PowerShell does not use stdout, but WriteConsole, when writing to console. So, it need special logic to write to stdout, if it was redirected. But, it seems, for some reason, PowerShell does not use [Console]::IsOutputRedirected, but use its own logic, flawed for > nul case.
Thanks, @PetSerAl, for pointing out the internals. It's reasonable to expect PS to respect the invoking program's redirections, irrespective of PS's internals, and past PowerShell versions have done so. It sounds that you agree that it's a bug, right? Or was there some intentional change in behavior I'm missing?
For me, it looks like a bug. I can not think of any reasons for ignoring redirection to nul.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.