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..
Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.
All you have to do is to go to Out-String and add the -Width parameter. Keep in mind that the -Width parameter of Out-File cmdlet specifies the number of characters in each line of output. Any other characters will simply be truncated, not wrapped.
There are different ways to add newline to string or variable in PowerShell using carriage return `r or line continuation character ` at the end of code. Backtick (`) character is the PowerShell line continuation character. It ensures the PowerShell script continues to a new line.
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()
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With