Remove blank lines in powershell output
Asked Answered
D

5

20

I'm trying to remove blank lines before and after output but it's just not working. I tried Adding -NoNewLine after the very first Write-Host, but that only removes one blank line so far.

Code:

  $tag1 = "c91638"

    Write-Host "Operating System Information"


    $OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1 

    $OSInfo `
        | Format-List `
            @{Name="OS Name";Expression={$_.Caption}}, 
            @{Name="OS Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}, 
            @{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}}; 

    Write-Host "Line test.."

Outputs:

Operating System Information


OS Name         : Microsoft Windows 7 Enterprise 
OS Boot Time    : 8/27/2015 2:05:35 AM
OS Install Date : 4/4/2014 11:39:15 AM



Line test..

What I want to do:

Operating System Information

OS Name         : Microsoft Windows 7 Enterprise 
OS Boot Time    : 8/27/2015 2:05:35 AM
OS Install Date : 4/4/2014 11:39:15 AM

Line test..
Discomposure answered 27/8, 2015 at 14:52 Comment(1)
Something similar here which I found to be very helpful.Mcnair
H
30

Try this instead:

($OSInfo `
    | Format-List `
        @{Name="OS Name";Expression={$_.Caption}}, 
        @{Name="OS Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}, 
        @{Name="OS Install Date";Expression={$_.ConvertToDateTime($_.InstallDate)}}  `
    | Out-String).Trim()

That'll clean up all the extraneous blank lines produced by Format-List. You may need to insert a couple of your own that you get to control.

Hap answered 27/8, 2015 at 15:12 Comment(6)
I knew I was forgetting something.... Out-String. That works. I can add my own spaces.Discomposure
It also trims leading spaces, which I don't want. Any ideas?Maccabean
@PatrickSzalapski do you mean leading and trailing new lines rather than spaces?Hap
No, it trims leading space characters when I only want it to trim blank lines.Maccabean
@PatrickSzalapski I can't repro. Can you post a screenshot on imgur or somewhere. Also what version of PowerShell?Hap
Verison 7.2. Here's an example. tio.run/##rYyxDYAwEMR6pjjRAAVULEHPAETkRCKFD8q/…Maccabean
I
8

Just to add a remark, because I see this being done all the time, even now - Format-List and Format-Table should only be used to output text in the console.

If you have objects to output as text files, CSV etc, then you simply should Select-Object to grab the objects you want rather than ft or fl. Then you can apply your Out-String if text formatting is required.

The above example should be:

($OSInfo `
| Select-Object `
    @{Name="OS Name";Expression={$_.Caption}}, 
    ... `
| Out-String).Trim()
Inventor answered 18/9, 2016 at 5:38 Comment(4)
I am outputting it in the console so it's fine also. Thanks for the tip.Discomposure
What's the reason for that?Keramic
Because Format-List and Format-Table are for formatting output for display in the console. To select objects out of a pipeline, you should simply select them - then you're not dealing with whatever is going on under the hood with the formatting. Formatting the output for display on screen makes even less sense if you're exporting to CSV - the CSV is the format you want. Format-Table is a complete waste of time - Select, then Export-CSV does your formatting.Inventor
As I often see "The above example should be:" no longer has any relevant/context for "above" as questions get voted up/down. Perhaps you can edit it and add a link to whatever that WAS at Sep 18, 2016 at 5:38.Littrell
M
2

Using .Trim() goes too far in that it deletes leading & trailing spaces as well as blank lines. If you want to delete only blank lines, try this, after any code that results in a string, do:

$result.Trim("`r","`n")

Or for many strings, e.g. after Format-Table or similar:

$results | Format-Table | Out-String | ForEach-Object { $_.Trim("`r","`n") }

Maccabean answered 15/1, 2022 at 20:49 Comment(0)
U
2

You can also do this :

$result=yourCommandHere | Out-String
$result.Trim()

Or in a single line without using a variable :

(yourCommandHere | Out-String).Trim()
Uzziel answered 18/8, 2022 at 13:50 Comment(0)
B
0

Here is an all-in-one function to easily write list (as output result), blank lines are removed, it can be piped. 2 examples of use shown below Hope this help

function Write-List {
    Param(
        [Parameter(Mandatory, ValueFromPipeline)][array] $Array,
        [string]$Prefixe,
        [bool]$Numbering = $False
    )
    if ($Numbering) { 
        $NumberOfDigit = $($Array.Count).ToString().Length

        $Array | Format-List | Out-String -Stream | ForEach-Object -Process {
            if (-not [string]::IsNullOrWhiteSpace($_)) {
                "$Prefixe# {0,$NumberOfDigit} : {1}" -f (++$Index), $_
            }
        }
    } else {
        $Array | Format-List | Out-String -Stream | ForEach-Object -Process {
            if (-not [string]::IsNullOrWhiteSpace($_)) {
                "$Prefixe{0}" -f $_
            }
        }
    }
}

Example #1 :

Write-List @("titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata", "titi", "toto", "tata") -Numbering $True
#  1 : titi
#  2 : toto
#  3 : tata
#  4 : titi
#  5 : toto
#  6 : tata
#  7 : titi
#  8 : toto
#  9 : tata
# 10 : titi
# 11 : toto
# 12 : tata

Example #2 :

Get-Service -Name "*openvpn*" | Select-Object DisplayName,Name,Status,StartType | Write-List -Prefixe " - "
 - DisplayName : OpenVPN Interactive Service
 - Name        : OpenVPNServiceInteractive
 - Status      : Running
 - StartType   : Automatic
Botryoidal answered 5/1 at 22:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.