[英]Powershell directory structured into json format
您好,我是 powershell 的新手。
我正在嘗試使用 powershell 創建一個結構為 json 格式的目錄。 類似於下面的這些圖片
我研究了一些方法來做到這一點,發現這是一種類似或更好的方式來將目錄和文件命名為 json 格式。
function Add-Tabstops{
param($Count)
$tabs = ""
for($i=0; $i -lt $Count; $i++){$tabs += " "}
return $tabs
}
function Output-JsonChildren{
param($Path, $Level = 1)
return $(Get-ChildItem -Path $Path | Where-Object{$_} | ForEach-Object{
(Add-Tabstops $Level) +
"{`n" +
(Add-Tabstops ($Level+1)) +
"`"name`"`: `"$($_.Name)`"," +
"`n" +
(Add-Tabstops ($Level+1)) +
"`"children`": ["+
$(if($_.psiscontainer){"`n" + (Output-JsonChildren -Path $_.FullName -Level ($Level+2))+ "`n" + (Add-Tabstops ($Level+1))}) +
"]`n" +
(Add-Tabstops ($Level)) +
"}"
}) -join ",`n"
}
$JSON = Output-JsonChildren -Path "C:\Users\Glen\Desktop\democontainer" | Out-File "C:\Users\Glen\Desktop\democontainer\test.json"
"["
$JSON
"]"
是的,這是可能的。
您將需要編寫一點遞歸 function 遍歷字典並為您收集信息。
您可以使用哈希表 ( @{}
) 或 PowerShell object,但最好使用哈希表。
Get-ChildItem
和ConvertTo-Json
是你的朋友
像這樣的東西:
function build-json {
param (
[string]$fullPath
)
$hashtable = @{}
$directories = get-childitem $fullPath -Directory
try{
$files = (get-childitem $fullPath -File)
if($null -eq $files) {
$hashtable.files = @()
}
else {
$hashtable.files = [array]$files.Name
}
}
catch {
echo 'xxx'
}
$hashtable.directories = @{}
foreach($directory in $directories) {
$element = Split-Path $directory.fullname -Leaf
$hashtable.directories.$element = build-json -fullPath $directory.FullName -hashtable $hashtable
}
return $hashtable
}
$sourcefolder = 'E:\xxx\Software\yyy\python392'
$result3 = build-json -fullPath $sourcefolder -hashtable @{}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.