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

14,537

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.

To fix both, expand the name out to just text, and generally use Set-Content instead:

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 
Share:
14,537
ikask
Author by

ikask

Updated on June 04, 2022

Comments

  • ikask
    ikask about 2 years

    I run this command and I get all computer hostnames in the names.txt file. 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  
    
  • ikask
    ikask over 7 years
    not working..getting something like @{name=AWS-TESTSERVER1} instead of AWS-TESTSEVER1
  • anthonybell
    anthonybell over 7 years
    I think that should do the trick. It is returning a hashtable where name=VALUE, so you can do foreach and select the key: %{ $_.name }
  • Moerwald
    Moerwald over 7 years
    I think the regex is incorrect. Try \s+$ instead.
  • LavaHot
    LavaHot over 6 years
    Thanks for the breakdown of the short forms. I didn't know the dot operator was the same as select-object!