Microsoft has a
support article explaining how to change the allow or deny policy of inviting external members to an Office 365 Group via PowerShell. This is all nice, but it doesn’t scale well in an automation scenario.
In my current project the default setting is to allow externals outside the organization to be invited, but through a custom groups order form, you can choose to block external parties – which is useful for internal only projects.
So how do you go about this?
Prerequisites
As I’m doing automation using Office 365 app tokens via the Microsoft Graph, the following scopes are needed when working with Groups and Directory objects (and remember to admin consent) :
- Group.ReadWrite.All
- Directory.ReadWrite.All
- User.Read.All (needed when adding owners/members)
Applying the template
I followed the support article for PowerShell which tells you to apply a template named
Group.Unified.Guest which has the id
08d542b9-071f-4e16-94b0-74abb372e3d9 to the group, setting
AllowToAddGuests to true or false, depending on if you want to allow external members or not.
A word of caution: The functionality of working with directory objects via the Microsoft Graph is only available at the beta end-point at the time of writing. But as long as it works I’m good to go, and I’ll monitor if the API changes and when it moves to GA.
The code uses Office PnP PowerShell to connect to the Microsoft Graph, creates a new Office 365 group, retrieves the app access token which is then used in a manual web request to apply a policy to the newly created group. Adapting the sample to your scenario should be easy enough, as it’s the web request applying the actual policy. If you're curious, we're using Azure web jobs to poll the order list, and uses PnP PowerShell like below for the automation.
#Connect to the Graph
Connect-PnPMicrosoftGraph -AppId $appId -AppSecret $appSecret -AADDomain tenant.onmicrosoft.com
#Create a new group
$group = New-PnPUnifiedGroup -MailNickname $mailAlias -DisplayName $displayName -Description $description -IsPrivate:$private -Owners $owner -Members $members
#Get the access token
$token = Get-PnPAccessToken
#Prepare headers
$headers = @{"Content-Type" = "application/json" ; "Authorization" = "Bearer " + $token}
#The directory template to set the policy
$templateDeny = @"
{
"templateId": "08d542b9-071f-4e16-94b0-74abb372e3d9",
"values": [
{
"name": "AllowToAddGuests",
"value": "False"
}
]
}
"@
#Graph URL to add settings to the group
$url = "https://graph.microsoft.com/beta/groups/$($group.GroupId)/settings"
#Apply the template, and wait for a 204
Invoke-WebRequest -Method Post -Uri $url -Headers $headers -Body $templateDeny