2016-08-22 58 views
0

我有一個我正在構建的腳本,通過文件樹遞歸,構建一個對象來表示該樹,並以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 
} 
+1

您能否提供一個您想要的流程的JSON示例?我有一種感覺,你在這裏完成的代碼可能比需要的代碼更多。 – alroc

+0

也許,但我無法找到更好的方法。我已經將示例輸出添加到問題中。 – wmassingham

+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 
+0

這會產生我想要的輸出。你能解釋一下你如何使用ForEach-Object的語法嗎? – wmassingham

+0

@ wmassingham'1..3 | ForEach-Object {'Begin'} {「Process $ _」} {'End'}'我只使用全部三個('Begin','Process'和'End')塊,而不僅僅是'Process'塊。 – PetSerAl