我有以下代碼:
$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 中顯示的布局相同的輸出檔案?
uj5u.com熱心網友回復:
只是一些事情:
- 使您的函式輸出字串而不是 using
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://www.uj5u.com/houduan/331882.html
