wmassingham wmassingham - 3 months ago 8
JSON Question

Recursing through directories: child objects showing up blank?

I have a script I'm building to recurse through a file tree, build an object to represent that tree, and print it out in JSON. However, for some reason, the child objects are showing up blank when I try to print them. Here's the code I have so far:

$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


Here's what I'm trying to get the final output to look like:

{
"updatepackage": {
"log": {
"DELLMUP.log": 5632
}
"New Text Document.txt": 0
}
"list.csv": 588
}

Answer

I think, you better to rewrite recurse to return object representing directory rather than modify one passed by parameter:

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