如何让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
相关产品推荐
相关产品推荐

