PowerShell中获取Graph对象属性信息并实现属性对比
Graph对象属性对比与差异检测问题
需求背景
我需要解析Graph命令(比如Get-MgGroup)返回对象的参数,获取每个属性的名称、类型及对应值,然后在PowerShell中用Compare-Object工具对比对象的当前状态与JSON/数组格式传入的bodyparams参数。最终要实现一个通用函数,对比新旧参数后生成差异参数集,以此构建无需手动修改的通用修改模板,适配任意对象的变更场景。
当前尝试与问题
- 已实现将对象转换为JSON:
Get-MgGroup -GroupId $GroupId | Select-Object * | Convertto-Json
该命令能返回带属性名和值的JSON结构,但我希望直接从对象本身获取完整属性信息。
- 通过以下命令获取NoteProperty信息:
Get-MgGroup -GroupId $GroupId | Select-Object * | Get-Member -MemberType NoteProperty
可以得到属性名称、成员类型和定义,但属性值类型多样(不只是null或字符串),无法直接用空对象填充null值。
- 编写了对比函数,但存在问题:
修改JSON中的AcceptedSenders属性为true后,Compare-Object未能正确识别该差异,即使将JSON中的空值替换为字符串'null'也无法解决。
对比函数代码:
function Compare-Attributes { Get-MgGroup -GroupId $GroupId | Select-Object -Property * | ConvertTo-Json -Compress | Out-file -FilePath 'C:\Users\Currentusr\Currentdir\BodyParams.JSON' ### 修改部分值 $old_parms = @(Get-MgGroup -GroupId $GroupId | Select-Object -Property * | ConvertTo-Json ) $new_parms = @(Get-Content 'C:\Users\Currentusr\Currentdir\BodyParams.JSON' | Convertfrom-Json ) $new_parms = @(Get-Content 'C:\Users\YassinBousaadi\projects\Ansible\Ansible_Modules\BodyParams.JSON' | Convertfrom-Json | Edit-LeafProperty -PassThru { if ($null -eq $_.Value) { $_.Value = 'null' } } | ConvertTo-Json) $old_parms_obj = @( $old_parms| ConvertFrom-Json) $new_parms_obj = @( $new_parms | ConvertFrom-Json) echo $new_parms_obj Compare-Object -ReferenceObject $old_parms_obj ` -DifferenceObject $new_parms_obj ` -IncludeEqual ` }
内容的提问来源于stack exchange,提问作者Yb-1245843
相关产品推荐
相关产品推荐

