Home > Back-end >  How to output PowerShell tree to text or Excel file
How to output PowerShell tree to text or Excel file

Time:10-23

I've the following code:

$readPath = "C:\FirstFolder"
$writePath = "C:\SecondFolder"

Function Recurse($folder, $lvl) {

    Get-ChildItem -Path $folder -File | ForEach-Object {
        Write-Host "$("  "*$lvl)> $($_.Name) - $((Get-Acl -Path $_.FullName).Owner)"
    }

    Get-ChildItem -Path $folder -Directory | ForEach-Object {
        Write-Host "$("  "*$lvl)> $($_.Name)"
        Recurse -folder $_.FullName -lvl $($lvl 1)
    }

}

$root = Get-Item -Path $readPath
Recurse -folder $root.FullName -lvl 0

which gives an output like this:

> File0.xlsx - OwnerB
> Directory1
  >File1.1.txt - OwnerB
  >File1.2.ppt - OwnerA
>Directory2
  >File2.1 - OwnerA
  >File2.2 - OwnerA

When I add the code $log | Out-File $writePath\OwnerTree.txt -Encoding UTF8, my output file is blank.

Anyone know how to get an output file with the same layout as what appears in PowerShell?

CodePudding user response:

Just a few things:

  1. Make your function output the strings instead of using Write-Host, of which the sole purpuse is to write to the console screen for display
  2. capture the result of your function in a variable and save that to a file
  3. If you want to write both to file AND to the console, use Set-Content instead of Out-File, because that also has a switch -PassThru
function Get-OwnerTree ([string]$folder, [int]$lvl) {
    Get-ChildItem -Path $folder -File | ForEach-Object {
        "$("  "*$lvl)> $($_.Name) - $((Get-Acl -Path $_.FullName).Owner)"
    }

    Get-ChildItem -Path $folder -Directory | ForEach-Object {
        "$("  "*$lvl)> $($_.Name)"
        Get-OwnerTree -folder $_.FullName -lvl (  $lvl)
    }

}

$root = Get-Item -Path $readPath
$log = Get-OwnerTree -folder $root.FullName -lvl 0

$log | Set-Content -Path "$writePath\OwnerTree.txt" -Encoding UTF8 -PassThru

I have also changed the function name to comply with PowerShell's Verb-Noun naming convention

  • Related