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

PowerShell遍历JSON对象修改AD用户属性问题求助

用PowerShell处理AD用户属性更新的JSON数据

背景与JSON示例

需要用PowerShell更新Active Directory(AD)用户属性,已创建包含4000+用户的JSON文件,示例内容如下:

{
   "xyz" : {
      "title" : "Leerling Copernicus SG, klas: 2MH1A",
      "displayName" : "Student xyz",
      "surname" : "xyz"
   },
   "abc" : {
      "displayName" : "Student abc",
      "givenname" : "Student"
   }
}

初始JSON转换命令

通过以下命令将JSON文件转换为PowerShell对象:

$json = Get-Content -Path 'C:\somewhere\mutaties.json' -Raw|ConvertFrom-Json

遇到的问题

尝试用以下代码遍历对象时无法正常工作,首次循环中$user包含了整个对象,同时不清楚如何获取xyz、abc这类账号键以及属性名称:

foreach ($user in $json) {
  foreach ($property in $user) {
    // do something smart
  }
}

可行解决方案

自行写出的可行代码如下,虽不够精巧但能解决问题:

$jsonObject = Get-Content -Path 'C:\somewhere\mutaties.json' -Raw|ConvertFrom-Json

foreach ($user in $jsonObject.psobject.Properties) {
    $key =  $user.name
    $properties = $user.VALUE
    write-host $key

    foreach ($property in $properties.psobject.Properties) {
        $name = $property.Name
        $value = $property.VALUE
        write-host `t $name`t $value
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:57:03