简体   繁体   English

powershell out-file如何消除每行上的多余空间

[英]powershell out-file how to rid of extra spaces on each line

I run this command and I get all computer hostnames in the names.txt file. 我运行此命令,并在names.txt文件中获得了所有计算机的主机名。 Each hostname in the file is on a separate line, but every hostname is followed with white spaces which cause an issue when I try to read this file. 文件中的每个主机名都位于单独的行中,但是每个主机名后都带有空格,这在我尝试读取此文件时会引起问题。 How can I output to this file without getting the white spaces on each line? 如何在不获取每行空白的情况下输出到此文件?

Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | out-file -filepath C:\temp\names.txt  

You have the problem that you don't just have names, you have objects with the property 'name', and you also have the problem that Out-File runs complex objects through some kind of formatting before sending them to the file. 您会遇到这样的问题:您不仅拥有名称,还拥有带有“名称”属性的对象,并且还存在Out-File在将复杂对象发送到文件之前通过某种格式运行它们的问题。

To fix both, expand the name out to just text, and generally use Set-Content instead: 要同时解决这两个问题,请将名称扩展为仅文本,通常使用Set-Content

Get-ADComputer -filter * | Select-Object -ExpandProperty Name | Sort-Object | Set-Content C:\temp\names.txt 

or in short form 或简写形式

Get-ADComputer -filter * | Select -Expand Name | Sort | sc C:\temp\names.txt 

or 要么

(Get-ADComputer -filter *).Name | sort | sc C:\temp\names.txt 

Piping it through this should work (before piping to the out-file): 通过它进行配管应该起作用(在配管到外文件之前):

EDIT : Piping through % { $_.name } should convert @{name=VALUE} to VALUE: 编辑 :通过% { $_.name }配管应将@ {name = VALUE}转换为VALUE:

 % { $_ -replace ' +$','' } | % { $_.name }

Like this: 像这样:

Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | % { $_ -replace ' +$','' } | % { $_.name } | out-file -filepath C:\temp\names.txt

expandproperty should get rid of the @() expandproperty应该摆脱@()

Get-ADComputer -Filter * | sort Name | Select -expandproperty Name | %{ $_.TrimEnd(" ") } | out-file -filepath C:\temp\names

Untested no AD@home 未经测试没有AD @ home

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM