如何将 PowerShell 树输出到文本或 Excel 文件

How to output PowerShell tree to text or Excel file

我有以下代码:

$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

输出如下:

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

当我添加代码 $log | Out-File $writePath\OwnerTree.txt -Encoding UTF8 时,我的输出文件是空白的。

有人知道如何获得与 PowerShell 中显示的布局相同的输出文件吗?

只是一些事情:

  1. 使您的函数输出字符串而不是使用Write-Host,其唯一目的是写入控制台屏幕以供显示
  2. 在变量中捕获函数的结果并将其保存到文件
  3. 如果你想同时写入文件和控制台,请使用 Set-Content 而不是 Out-File,因为它也有一个开关 -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

我还更改了函数名称以符合 PowerShell 的 Verb-Noun 命名约定