Powershell 2.0 out-file formatting nightmare


How can I get Powershell to output a file IDENTICAL to the file produced by the following command?

dir /s /b /a-d *.* > C:\files.txt

should be easy, right?!!

EDIT: I found ps was truncating the output based on the screen buffer width. Fix that with format-table and it pads with spaces... try format-list and you get property headings...you get the idea.


There are many ways to write information to a file. One is Set-Content, which does not have the width problem. Also, converting a FileInfo object to a string results in the FullName.

dir * -r | ?{!$_.PSIsCcontainer} | Set-Content C:\files.txt

The reason you have a problem with Out-File is that all the Out-* cmdlets use the automatic formatting views. Those views are created with the console in mind.

Does it have to be exact? Why? As the saying goes, if you're parsing strings in Powershell, you're probably doing something wrong...anyway...

1) Just call into cmd.exe.

PS> cmd /c "dir /s /b /a-d *.* > c:\files.txt"

2) I believe you can get the same results from native Powershell. But I can't be responsible for testing every edge case with NTFS junctions, hidden files, etc.

PS> gci -r | ?{ !$_.psiscontainer } | %{ $_.fullname } | out-file c:\files.txt

I personally hate the fact you can't use "select" to retrieve the FullName property without weird side effects on downstream cmdlets. If the pointlessness of the foreach loop bothers you as much as it does me, use Get-PropertyValue from PSCX or Linq-Select from Josh Einstein.

This video can help you solving your question :)
By: admin