0

I have the following script:

Get-ChildItem $rootPath -Recurse | 
    Where-Object {$_.PSIsContainer} | 
    Where-Object {(Get-ChildItem $_.FullName | Where-Object {!$_.PSIsContainer}|  Measure-Object | Select-Object -ExpandProperty Count) -gt 0} |
    ForEach-Object{

        $files = Get-ChildItem $_.FullName

        $props = @{
            Path = $_.FullName
            Size = "{0:N0}" -f (($files | Where-Object {!$_.PSIsContainer} |  Measure-Object -Sum Length | Select-Object -ExpandProperty Sum))
            Count = $files | Measure-Object | Select-Object -ExpandProperty Count
        }

        If ($files.Extension -match "L\d\d"){
            # These are special files and we are assuming they are alone in the directory
            # Change the path
            $props.Path = $files | Select-Object -First 1 | Select-Object -ExpandProperty FullName
        }

        New-Object -TypeName PSCustomObject -Property $props

} | Select Path,Size,Count

How can I write the output to a textfile instead of to the console?

Pr0no
  • 3,910
  • 21
  • 74
  • 121
  • possible duplicate of [Write output to text file in Powershell](http://stackoverflow.com/questions/18469104/write-output-to-text-file-in-powershell) – Vesper Jul 17 '15 at 13:00

2 Answers2

4

Forward that to Out-File. For example:

Get-ChildItem ...
<skipped>
} | Select Path,Size,Count | Out-File "files.txt"
Vesper
  • 18,599
  • 6
  • 39
  • 61
2

A couple of things. You have other options here worth mentioning.

} | Select Path,Size,Count | Set-Content "files.txt"

Set-Content would also work and has the advantage of defaulting to ACSII encoding. If performance comes into play then using .Net StreamWriter will beat Set-Content and Out-File out anyway.

More importantly this code was designed to output objects. Working with that you should use Export-CSV to have nicely formatted output.

} | Select Path,Size,Count | Export-Csv -NoTypeInformation "files.csv"
Matt
  • 45,022
  • 8
  • 78
  • 119