如何将PowerShell生成的目录树输出到文本或Excel文件
PowerShell控制台输出导出为同格式文本文件解决方案
问题原因
你得到空白文件的核心原因是Write-Host cmdlet的特性:它只会把内容直接输出到PowerShell控制台宿主,不会写入标准输出流,因此你无法通过$log变量捕获到任何内容,导出的文件自然为空。
修正后完整代码
将所有Write-Host替换为直接返回字符串到输出流,再统一捕获递归函数的所有输出后导出即可,布局和控制台显示完全一致:
$readPath = "C:\FirstFolder" $writePath = "C:\SecondFolder" Function Recurse($folder, $lvl) { # 处理文件输出 Get-ChildItem -Path $folder -File | ForEach-Object { "$(" "*$lvl)> $($_.Name) - $((Get-Acl -Path $_.FullName).Owner)" } # 处理目录输出+递归 Get-ChildItem -Path $folder -Directory | ForEach-Object { "$(" "*$lvl)> $($_.Name)" Recurse -folder $_.FullName -lvl ($lvl+1) } } $root = Get-Item -Path $readPath # 捕获所有递归输出到变量 $log = Recurse -folder $root.FullName -lvl 0 # 导出为UTF8编码的文本文件 $log | Out-File "$writePath\OwnerTree.txt" -Encoding UTF8
可选优化
如果你需要同时在控制台显示输出、同时写入文件,可以将最后两行替换为Tee-Object实现双向输出:
$root = Get-Item -Path $readPath Recurse -folder $root.FullName -lvl 0 | Tee-Object -FilePath "$writePath\OwnerTree.txt" -Encoding UTF8
内容的提问来源于stack exchange,提问作者MConvery
相关产品推荐
相关产品推荐

