PowerShell: Remove Blank Lines from Command Output

For some reason, when you run some shell commands in a PowerShell script, the output has an extra blank line after each line. It doesn’t seem to affect commands run in the console, but it is evident using the command line in the PowerGUI Script Editor. Examples are ipconfig and tracert.

The thing to keep in mind is that when you run a shell command, you are actually getting back an array of objects, one item per line.

You can remove all empty lines with a where clause:

ipconfig /all | where {$_ -ne ""}

but that also removes lines that ipconfig intentionally output as blank.

Here’s a little script to only remove even-numbered blank lines. Well actually, it outputs all odd-numbered lines, and any non-blank lines (regardless of number):

# Assume first line is not blank, and every second line after that 
# is blank. Print non-blank lines and any odd-numbered lines (even 
# if blank). Since array is 0-based, we actually print if index is 
# even (modulo 2 = 0).
ipconfig /all | ForEach-Object {
    if (($_ -ne "") -or ($i % 2 -eq 0)) { $_ }

Here’s another way to do the same thing, based on an idea in this article. It has fewer lines of code but in my opinion is harder to read:

$Temp = ipconfig /all
for($i = 0; $i -lt $Temp.Count; $i++) {
    if ( ($Temp[$i] -ne "") -or ($i %2 -eq 0) ) { $Temp[$i] } 

Any other suggestions? Or anyone know how to suppress the extra lines in the first place when running shell commands?

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.