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

