1

I have this code to list how many files I have in each subdirectory

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

and it works awesome. But now I like to save it as a file the result and now I have problem.

I has tried with three different ways but the only thing it does is create the file but there is nothing in it.

I have try with

| Export-Csv -Path .\data1.csv -NoTypeInformation
| Out-File -FilePath .\data1.txt

and even

>> Data.txt
Cazz
  • 51
  • 7

1 Answers1

2

You're using Write-Host. Write-Host displays text but doesn't write it anywhere.

You can use Write-Output

dir -recurse |  ? { $_.PSIsContainer } | % { Write-Output $_.FullName (dir $_.FullName | Measure-Object).Count } | Out-File -FilePath $PSScriptRoot\Log.txt

Or you could just skip it:

dir -recurse |  ? { $_.PSIsContainer } | % { $_.FullName + ' ' + (dir $_.FullName | Measure-Object).Count } | Out-File -FilePath $PSScriptRoot\Log.txt

Here's old article about streams: https://devblogs.microsoft.com/scripting/understanding-streams-redirection-and-write-host-in-powershell/

What the article doesn't cover due to its age is the PSv5+ information stream (number 6), to which Write-Host now writes - see help topic about_Redirection

mklement0
  • 382,024
  • 64
  • 607
  • 775
MadBoy
  • 10,824
  • 24
  • 95
  • 156