21

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..
1
  • Something similar here which I found to be very helpful. Commented Jul 13, 2017 at 9:02

6 Answers 6

31

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I knew I was forgetting something.... Out-String. That works. I can add my own spaces.
It also trims leading spaces, which I don't want. Any ideas?
@PatrickSzalapski do you mean leading and trailing new lines rather than spaces?
No, it trims leading space characters when I only want it to trim blank lines.
@PatrickSzalapski I can't repro. Can you post a screenshot on imgur or somewhere. Also what version of PowerShell?
|
9

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()

4 Comments

I am outputting it in the console so it's fine also. Thanks for the tip.
What's the reason for that?
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.
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.
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") }

Comments

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()

Comments

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

Comments

0
\# A TRIM() FUNCTION ( AND A USEFUL ALIAS ):

function tr { Param( \[Parameter(Mandatory, ValueFromPipeline)\]\[array\] $Array) $Array | Out-String | ForEach { $\_.trim() }}

set-alias grep select-string

\# Test IT :

cd $HOME

ls | grep "pictures" | tr

5 Comments

function tr { foreach ($object in $input) { if (-not [string]::IsNullOrWhiteSpace($object) ) { "$object" -f $object } } }
ABOVE A CORRECTION FOR TR FUNCTION (SORRY MY BAD ...)
function tr { foreach ($object in $input) { "$object" -f $object } }
^^^ SHORTER WAY IS BETTER ^^^
Thank you for your interest in contributing to the Stack Overflow community. This question already has existing answers. It would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.