Remove blank lines in powershell output

喜夏-厌秋 提交于 2019-12-05 19:52:22

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/32252707/remove-blank-lines-in-powershell-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!