Search code examples
jsonazurepowershellazure-active-directory

Using Powershell, how do I convert Azure AD Group members into a Json object (file) which I can then update?


I am wondering the best approach to create a single Powershell script that does the following:

  1. Obtains the email addresses of AAD group members using the following method (or some other) and converts it into a Json object
$AADGroup = "ExampleGroup1"

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

The output of the above looks like this:

[
    {
        "Mail":  "[email protected]"
    },
    {
        "Mail":  "[email protected]"
    }
]
  1. Now that's fine, but what if i want to update this Json file/object by adding a new User, let's say '[email protected]' that is taken as an element from a string array as follows?
$UserName = @('[email protected]')

There is this approach, and I suppose also another approach possibly where you could add the new user as part of the query command before using the ConvertTo-Json? Not sure which one could work best.

Thanks.


Solution

  • You can use a single script block ({ ... }) invoked via the call operator (&) in order to output both the original users' addresses and the to-be-added ones, both as single-property objects with a .Mail property, and then convert the combined results to 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 @('[email protected]', '[email protected]') | 
      ConvertTo-Json
    

    Working only with objects and then converting to JSON is preferable to partially converting to JSON first, and then trying to update the JSON (something that PowerShell provides no direct support for).