PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] How to output PowerShell tree to text or Excel file

 August 14, 2022     output, powershell, txt     No comments   

Issue

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?


Solution

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



Answered By - Theo
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing