如何将PowerShell返回的结构化数组转换为规范JSON格式并解析
解决方案(PowerShell环境)
实现思路
- 原始数据为按行存储的字符串数组,空行为分组分隔符,无冒号的非空行为分组名称,含冒号的行是键值对
- 遍历每行字符串,按规则拆分键值、归类到对应分组下,最终组装为结构化自定义对象
- 生成的自定义对象可直接提取字段,也可直接转换为规范JSON格式
可用代码
# 初始化结果对象、当前分组标记 $systemInfo = [PSCustomObject]@{} $currentGroup = $null # 遍历原始数据数组的每一行 foreach ($line in $computerdata) { # 清理行首尾空白 $trimmedLine = $line.Trim() # 跳过空行 if ([string]::IsNullOrEmpty($trimmedLine)) { continue } # 判断是否为分组标题行(不含冒号) if ($trimmedLine -notmatch ':') { $currentGroup = $trimmedLine # 给结果对象新增分组属性 $systemInfo | Add-Member -NotePropertyName $currentGroup -NotePropertyValue ([PSCustomObject]@{}) -Force continue } # 拆分键值对,最多拆分为2部分,避免值中包含冒号导致拆分错误 $keyValue = $trimmedLine -split ':', 2 $key = $keyValue[0].Trim() $value = $keyValue[1].Trim() # 写入对应位置:无分组时写根级,有分组时写对应分组下 if ($null -eq $currentGroup) { $systemInfo | Add-Member -NotePropertyName $key -NotePropertyValue $value -Force } else { $systemInfo.$currentGroup | Add-Member -NotePropertyName $key -NotePropertyValue $value -Force } } # 字段提取示例 # 取根级字段 $systemInfo.Uptime $systemInfo.'IP Address' # 取分组下的字段 $systemInfo.'Operating System'.Version $systemInfo.System.Manufacturer # 转换为规范JSON格式并导出 $systemInfo | ConvertTo-Json -Depth 10 | Out-File "SystemInfo.json"
效果说明
生成的结构化对象支持任意字段提取,导出的JSON为嵌套结构,各层级字段清晰可直接调用。
内容的提问来源于stack exchange,提问作者cosmis
相关产品推荐
相关产品推荐

