You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell解析YAML文件异常:无法获取与JSON脚本一致的数据

解决PowerShell直接解析YAML提取数据的问题

问题背景

原本通过JSON脚本可从转换后的JSON文件提取指定字段并导出到CSV,但部分YAML因格式错误无法完成转换。改用powershell-yaml模块的ConvertFrom-YAML编写脚本后,无法得到与JSON脚本一致的结果,需实现无需转换文件、直接从YAML提取数据的方法。

可用的JSON脚本

Get-ChildItem "C:\Users\hhh\appdev\powershell-scripts\spConnections" -Filter *.json -PipelineVariable file | ForEach-Object {
    (Get-Content $_ -Raw | ConvertFrom-Json).PSObject.Properties.Value | Select-Object @(
        @{ N = 'FileName'; E = { $file.Name }}, 'Name', 'entity_id', 'contact_info', 'sp_endpoint'
    )
} | Export-Csv "C:\Users\hhh\appdev\powershell-scripts\dataexports\test.csv" -NoTypeInformation

原无法工作的YAML脚本

Get-ChildItem "C:\Users\hhh\appdev\targetfolder" -Recurse -Filter *.yaml -PipelineVariable file | ForEach-Object {
    (Get-Content $_ -Raw | ConvertFrom-Yaml).PSObject.Properties.Value | Select-Object @(
        @{ N = 'FileName'; E = { $file.Name }}, 'Name', 'entity_id', 'contact_info', 'sp_endpoint'
    )
} | Export-Csv "C:\Users\hhh\appdev\powershell-scripts\dataexports\test.csv" -NoTypeInformation

YAML文件示例

---
  sfg_hhh::production::standard_sp_connections:
  - name: RRRRR
    entity_id: WWWWWW
    contact_info: ggggg@ggggg.com
    sp_endpoint: CCCCC
    base_index: 0
    sso_initialization_and_signature_policy:
      signing_certificate_id: EEEEE 
      sp_initiated: 
        require_signed_authn_requests: false
    authentication_policy_contracts:
      - LDAPUser
    attribute_contract:

问题原因

JSON脚本中,ConvertFrom-Json返回的对象直接包含一个属性,其值为目标数组;但YAML解析后,根对象的唯一属性是sfg_hhh::production::standard_sp_connections,该属性的值才是包含目标数据的数组。原YAML脚本未正确定位到数组层级,导致提取的字段值为空。

修复后的YAML脚本

Get-ChildItem "C:\Users\hhh\appdev\targetfolder" -Recurse -Filter *.yaml -PipelineVariable file | ForEach-Object {
    # 直接定位到YAML中的目标数组属性
    (Get-Content $_ -Raw | ConvertFrom-Yaml).'sfg_hhh::production::standard_sp_connections' | Select-Object @(
        @{ N = 'FileName'; E = { $file.Name }}, 'name', 'entity_id', 'contact_info', 'sp_endpoint'
    )
} | Export-Csv "C:\Users\hhh\appdev\powershell-scripts\dataexports\test.csv" -NoTypeInformation

关键说明

  • 精准定位数据层级:YAML解析后的数据结构中,目标数组嵌套在sfg_hhh::production::standard_sp_connections属性下,直接访问该属性即可获取需要处理的对象集合。
  • 字段名大小写匹配:YAML中的字段为小写的name,需与提取时指定的字段名保持一致,才能正确获取值。

内容的提问来源于stack exchange,提问作者Ben S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:55:25