【问题标题】:How to output PowerShell tree to text or Excel file如何将 PowerShell 树输出到文本或 Excel 文件
【发布时间】:2021-12-08 23:56:51
【问题描述】:

我有以下代码:

$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 中显示的布局相同的输出文件?

【问题讨论】:

    标签: powershell output txt write


    【解决方案1】:

    只有几件事:

    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 命名约定

    【讨论】:

    • 这似乎已经完成了 - 谢谢你,西奥!
    猜你喜欢
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2020-07-02
    • 2019-07-27
    相关资源
    最近更新 更多