如何将PowerShell树输出为文本或Excel文件 [英] How to output PowerShell tree to text or Excel file
本文介绍了如何将PowerShell树输出为文本或Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
$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 $writePathOwnerTree.txt -Encoding UTF8
时,输出文件为空。
有人知道如何获取与PowerShell中显示的布局相同的输出文件吗?
推荐答案
只有几件事:
- 使您的函数输出字符串,而不是使用
Write-Host
,因为Write-Host
的唯一用途是写入控制台屏幕进行显示 - 在变量中捕获函数结果并将其保存到文件
- 如果要同时写入文件和控制台,请使用
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 "$writePathOwnerTree.txt" -Encoding UTF8 -PassThru
我还更改了函数名称以符合PowerShell的Verb-Noun命名约定
这篇关于如何将PowerShell树输出为文本或Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文