我正在构建一个脚本来通过文件树进行递归,构建一个表示该树的对象,然后用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
}
答案 0 :(得分:1)
我认为,您最好重写recurse
以返回表示目录的对象,而不是修改通过参数传递的对象:
function recurse {
param($Dir)
Get-ChildItem -LiteralPath $Dir |
ForEach-Object {
$Obj = [ordered]@{}
} {
$Obj.Add($_.PSChildName, $(
if($_.PSIsContainer) {
recurse $_.PSPath
} else {
$_.Length
}
))
} {
$Obj
}
}
recurse c:\dell | ConvertTo-Json -Depth 100