AKAJim
AKAJim

Reputation: 47

Powershell - Output directory recurse to console and file

I'm outputting share folder structures to a text file using the code below:

$path = "\\server\share"
$file = "c:\share-folders.txt"
get-childitem "$path" -recurse -directory | select -expand fullname >> "$file"

I would also like to write it to the console at the same time as a way of tracking status. I've tried using tee-object to append the file and then pipe to write-host, but at best I have only been able to output to the text file, or to the console, but not both at once. Does anyone know the proper method to accomplish this?


Solution: Adding -Append to the end of the Tee-Object cmdlet resolved the issue.

$path = "\\server\share"
$file = "c:\share-folders.txt"
Get-ChildItem "$Path" -Recurse -Directory | Select -Expand FullName | Tee-Object -FilePath "$File" -Append

Upvotes: 1

Views: 6576

Answers (2)

Patrick
Patrick

Reputation: 2208

Or try this one:
First select the data and then foreach object add it to text file and write it to the console.

$path = "\\server\share"
$file = "c:\share-folders.txt"

Get-ChildItem "$path" -Recurse -Directory | Select-Object -ExpandProperty FullName | ForEach-Object {Add-Content -Value $_ -Path $file; Write-Host -Object $_}

Upvotes: 0

Schwarzie2478
Schwarzie2478

Reputation: 2276

This works for me

get-childitem "$path" -recurse -directory |  select -expand fullname | %{ Write-Output $_ ; $_ >> "$file"}

Following this, with the Tee commandlet:

get-childitem "$path" -recurse -directory |   select -expand fullname | tee -file  "$file"

Upvotes: 6

Related Questions