skip to Main Content

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.

2

Answers


  1. You could use and append to the object result. Something like this:

    $UserMail = @('[email protected]', '[email protected]')
    $AADGroup = "ExampleGroup1"
    
    $adMailList = Get-AzureADGroup -SearchString $AADGroup | Get-AzureADGroupMember | Select Mail | ConvertTo-Json
    foreach($mail in $UserMail){
        $adMailList += @{ Mail = $mail }
    }
    

    At the end, the result should be something like:

    [
        {
            "Mail":  "[email protected]"
        },
        {
            "Mail":  "[email protected]"
        },
        {
            "Mail":  "[email protected]"
        },
        {
            "Mail":  "[email protected]"
        }
    ]
    

    In case the result is not what you’re looking for, because it seems to be adding a HashTable instead of an object, then you could simply replace the inner foreach for:

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

    And that should do it

    Login or Signup to reply.
  2. You can use a single script block 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search