使用PowerShell,如何将Azure AD组成员转换为可以更新的JSON对象(文件)?

wyyhbhjk  于 2023-08-08  发布在  Shell
关注(0)|答案(2)|浏览(100)

我想知道最好的方法来创建一个单一的PowerShell脚本,执行以下操作:
1.使用以下方法(或其他方法)获取AAD组成员的电子邮件地址,并将其转换为Json对象

$AADGroup = "ExampleGroup1"

Get-AzureADGroup -SearchString $AADGroup | Get-AzureADGroupMember | Select Mail | ConvertTo-Json

字符串
上面的输出看起来像这样:

[
    {
        "Mail":  "user1@example.com"
    },
    {
        "Mail":  "user2@example.com"
    }
]


1.现在这很好,但是如果我想通过添加一个新的User来更新这个Json文件/对象,比如说'user3@example.com',它是从字符串数组中获取的元素,如下所示?

$UserName = @('user3@example.com')


有这种方法,我想也有另一种方法,在使用ConvertTo-Json之前,您可以将新用户添加为查询命令的一部分。不知道哪一个最好。

  • 谢谢-谢谢
yuvru6vn

yuvru6vn1#

您可以使用通过调用操作符(&)调用的单个script block{ ... }),以输出原始用户的地址和要添加的用户的地址,两者都作为具有.Mail属性的单属性对象,然后将组合结果转换为JSON:

& {
  param([string[]] $User)

  # Output the existing users (email addresses) as objects with a .Mail property.
  Get-AzureADGroup -SearchString $AADGroup | Get-AzureADGroupMember | Select-Object Mail

  # Convert the array of users (email addresses) to objects with a .Mail property.
  $User | ForEach-Object { [pscustomobject] @{ Mail = $_ } }

} -User @('user3@example.com', 'user4@example.com') | 
  ConvertTo-Json

字符串
只处理对象,然后 * 转换为JSON比先部分转换为JSON,然后尝试更新JSON(PowerShell不提供直接支持)更可取。

mznpcxlj

mznpcxlj2#

您可以使用并追加到对象结果。大概是这样的:

$UserMail = @('user3@example.com', 'user4@example.com')
$AADGroup = "ExampleGroup1"

$adMailList = Get-AzureADGroup -SearchString $AADGroup | Get-AzureADGroupMember | Select Mail | ConvertTo-Json
foreach($mail in $UserMail){
    $adMailList += @{ Mail = $mail }
}

字符串
最后,结果应该是这样的:

[
    {
        "Mail":  "user1@example.com"
    },
    {
        "Mail":  "user2@example.com"
    },
    {
        "Mail":  "user3@example.com"
    },
    {
        "Mail":  "user4@example.com"
    }
]


如果结果不是你想要的,因为它似乎添加了一个HashTable而不是一个对象,那么你可以简单地替换内部的foreach:

$adMailList += [PSCustomObject]@{ Mail = $mail }


这样就可以了

相关问题