结构化为json格式的Powershell目录
你好,我是powershell的新手 我正在尝试使用powershell创建一个json格式的目录。与下图类似 我研究了一些方法,发现这与将目录和文件命名为json格式类似或更好结构化为json格式的Powershell目录,json,powershell,Json,Powershell,你好,我是powershell的新手 我正在尝试使用powershell创建一个json格式的目录。与下图类似 我研究了一些方法,发现这与将目录和文件命名为json格式类似或更好 function Add-Tabstops{ param($Count) $tabs = "" for($i=0; $i -lt $Count; $i++){$tabs += " "} return $tabs } function Outp
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
"]"
是的,有可能
您将需要编写一个小的递归函数,它遍历字典并为您收集信息
您可以使用哈希表(@{}
)或PowerShell对象,但最好使用哈希表
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 @{}
@JeremyCaney,我已经结束了前一个问题,作为这个问题的重复。你能给我一个例子来帮助我开始使用HastTable吗?如果这对你有效,为什么不直接使用它呢?正如fpr
一样,它们是将目录和文件命名为json格式的类似或更好的方法吗?
这是什么意思?做事总是有更好的方法,但需要有一个更好的目标。也就是说,更快、更优雅的代码、更少的代码等等。您并不是在说为什么要更改它。至于示例。。。使用hasttable
,PowerShell帮助文件通过示例以及web上的许多文章/示例/视频显示了这一点。