我有一個我正在構建的腳本,通過文件樹遞歸,構建一個對象來表示該樹,並以JSON打印出來。但是,由於某種原因,當我嘗試打印它們時,子對象顯示爲空白。下面的代碼我到目前爲止:通過目錄遞歸:顯示空白的子對象?
$dir = "c:\dell"
# Top-level object to hold the directory tree
$obj = @{}
function recurse($dir, [ref]$obj) {
write-host "recursing into $dir"
# Object to hold this subdir & children
$thisobj = @{}
# List the files & folders in this directory
$folders = Get-ChildItem $dir | Where-Object { $_.PSIsContainer -eq $true }
$files = Get-ChildItem $dir | Where-Object { $_.PSIsContainer -eq $false }
#write-host $folders
# Iterate through the subdirs in this directory
foreach ($f in $folders) {
# Recurse into this subdir
recurse $f.fullname ([ref]$thisobj)
}
# Iterate through the files in this directory and add them to
foreach ($f in $files) {
write-host " - adding file to thisobj: $f"
$thisobj | add-member -MemberType NoteProperty -Name $f -value 10
}
# Print out this subtree
"$dir thisobj: "
$thisobj | convertto-json -depth 100
# Add this subtree to parent obj
$obj | Add-Member -MemberType NoteProperty -name $dir -value $thisobj
write-host "finished processing $dir"
}
# Initial recursion
recurse $dir ([ref]$obj)
write-host "final obj:"
$obj | ConvertTo-Json -depth 100
這裏就是我想要得到最終的輸出看起來像:
{
"updatepackage": {
"log": {
"DELLMUP.log": 5632
}
"New Text Document.txt": 0
}
"list.csv": 588
}
您能否提供一個您想要的流程的JSON示例?我有一種感覺,你在這裏完成的代碼可能比需要的代碼更多。 – alroc
也許,但我無法找到更好的方法。我已經將示例輸出添加到問題中。 – wmassingham
你的腳本應該做什麼? –