0

In recursively-count-files-in-subfolders a great working piece of PowerShell code writes to the screen. David comments later that you can redirect to file, but I can't get that to work. I have tried to place it in all kind of different places, but I keep ending up with output writing to screen and an empty file being created.

This is the syntax I would think would work:

dir -recurse |  ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count } | Out-File -FilePath FileCount.txt

It is probably super-simple, but for some reason, the logic behind PowerShell syntax keeps eluding me.

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

Don't use Write-Host in that spot. It will not send information down the pipeline to Out-File.

Example:

Get-ChildItem -recurse |  
Where-Object{ $_.PSIsContainer } | 
ForEach-Object{ ( $_.FullName + " " + (Get-ChildItem $_.FullName | Measure-Object).Count ) } | 
Out-File -FilePath FileCount.txt

About_Redirection .

What you are really looking for is Write-Output, but that is implied in the example. Above assumes a space as the separator between the path and the count.

An aside: you can use Get-ChildItem -Directory instead of Where-Object{ $_.PSIsContainer }

A more concise example:

Get-ChildItem -Recurse -Directory |  
ForEach-Object{ ( $_.FullName + " " + (Get-ChildItem $_.FullName).Count ) } | 
Out-File -FilePath FileCount.txt

Here I use the -Directory parameter on Get-ChildItem (Dir) instead of the Where-Object{ $_.PSIsContainer } and the .Count property instead of Measure-Object.

halfer
  • 19,824
  • 17
  • 99
  • 186
Steven
  • 6,817
  • 1
  • 14
  • 14
0

Modify Write-Host to Write-Output and you're there with you're required output in the file!

  • I cited `Write-Output` in my previous answer. However, there's no reason to actually use it and it is atypical to do so. Unless otherwise consumed everything PowerShell emits is output written to the pipeline. – Steven Aug 21 '20 at 14:24
  • Thank you Spandana – Ruud Hakkesteegt Aug 24 '20 at 20:29