我有以下代码:
$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 中显示的布局相同的输出文件吗?
只是几件事:
- 使你的功能output字符串而不是使用
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 "$writePath\OwnerTree.txt" -Encoding UTF8 -PassThru
我还更改了函数名称以符合 PowerShell 的要求动词名词 https://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/reference/docs-conceptual/developer/cmdlet/approved-verbs-for-windows-powershell-commands.md命名约定
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)