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

如何让PowerShell按JSON原定义顺序显示NoteProperty属性?

解决PowerShell中按JSON原始顺序获取NoteProperty属性的问题

你遇到的问题是Get-Member -MemberType NoteProperty会自动对属性名称排序,导致无法保留JSON定义的原始属性顺序。

核心思路

Get-Member默认会对输出的成员按名称排序,而PowerShell对象的PSObject.Properties集合会严格保留JSON解析后的原始属性顺序,我们可以直接从这个集合中筛选NoteProperty类型的属性。

修改后的代码

$JsonConfig = @"
    {
        "PostStep": {
            "AppExists": {
                "AppName": "Agent"
            },
            "Version": {
                "Number": "2.3"
            },
            "Execution": {
                "Argument": "/uninstall",
                "Installer": "C:\\WFBS\\Tool.exe"
            }
        }
    }
"@

$OrderedObject = $JsonConfig | ConvertFrom-Json
$StepObject = $OrderedObject.PostStep

# 直接从PSObject.Properties中筛选NoteProperty,保留原始顺序
foreach ($Property in $StepObject.PSObject.Properties.Where({ $_.MemberType -eq 'NoteProperty' })) {
    Write-Host $Property.Name
}

输出结果

AppExists
Version
Execution

补充说明

  • PSObject.Properties返回的是对象的属性集合,其顺序完全匹配JSON输入中的定义
  • Where({ $_.MemberType -eq 'NoteProperty' })替代了Get-Member -MemberType NoteProperty的筛选逻辑,同时避免了排序问题
  • 该方案兼容PowerShell 5.1及以上版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:52:09