如何在PowerShell中批量提取JSON中的所有Path值?
提取JSON中所有
path值的PowerShell解决方案 原始JSON数据
{ "vaults": { "43371adf": { "path": "C:\\Users\\user23\\Documents\\Mango Vault", "ts": 16767 }, "54a80cfadc691ec4": { "path": "C:\\Users\\user23\\Documents\\Apple Vault", "ts": 166576 }, "af524734": { "path": "C:\\Users\\user23\\Documents\\Orange Vault", "ts": 166985 }, "40290aab5": { "path": "C:\\Users\\user23\\Documents\\Banana Vault", "ts": 167293, "open": true } }, "frame": "hidden" }
问题分析
你尝试用where相关语法获取所有path值,但$vaultsIndex.vaults是包含多个动态Vault ID属性的对象,直接用where无法遍历这些子属性,因此返回错误结果。
可行解决方案
方法1:通过PSObject.Properties遍历子对象
直接访问对象的属性集合,提取所有子对象的path值:
$vaultsIndex = Get-Content -Path "C:\Temp\sample.json" | ConvertFrom-Json $vaultsIndex.vaults.PSObject.Properties.Value | ForEach-Object { $_.path }
方法2:简化的单行写法
将命令合并为一行,更简洁:
(Get-Content "C:\Temp\sample.json" | ConvertFrom-Json).vaults.PSObject.Properties.Value.path
方法3:用Get-Member遍历属性名
通过Get-Member获取所有Vault ID属性,再逐个提取对应path:
$vaultsIndex = Get-Content -Path "C:\Temp\sample.json" | ConvertFrom-Json $vaultsIndex.vaults | Get-Member -MemberType NoteProperty | ForEach-Object { $vaultsIndex.vaults.$($_.Name).path }
为什么之前的方法无效
你之前的$_.where -eq 'path'是错误用法:
where是PowerShell的过滤方法,需要传入脚本块(如{ $_.path -ne $null }),不是用来匹配属性名的$vaultsIndex.vaults的直接子属性是各个Vault ID,而非path,因此无法直接通过属性名匹配
内容的提问来源于stack exchange,提问作者gaberiel__
相关产品推荐
相关产品推荐

