Prevent Guests from being added to a specific Microsoft 365 Group or Microsoft Teams team
Summary
By default, guest access for Microsoft 365 groups is enabled within the tenant. This can be controlled either to allow or block guest access at the tenant level or for individual Microsoft 365 groups / Microsoft Teams team. For more information, check out Manage guest access in Microsoft 365 groups.
This script will enable or disable adding guests to a Microsoft 365 Group or Microsoft Teams team.
param (
[Parameter(Mandatory = $true)]
[string] $domain,
[Parameter(Mandatory = $true)]
[ValidateSet("true", "false")]
[string] $allowToAddGuests
)
$adminSiteURL = "https://$domain-Admin.SharePoint.com"
$dateTime = "_{0:MM_dd_yy}_{0:HH_mm_ss}" -f (Get-Date)
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$fileName = "m365_disable_addguests" + $dateTime + ".csv"
$outputPath = $directorypath + "\"+ $fileName
if (-not (Test-Path $outputPath)) {
New-Item -ItemType File -Path $outputPath
}
Connect-PnPOnline -Url $adminSiteURL -Interactive -WarningAction SilentlyContinue
# amend as required to be the correct filter
$report = Get-PnPMicrosoft365Group -Filter "startswith(displayName, 'test')" | ForEach-Object {
$group = $_
$groupSettings = Get-PnPMicrosoft365GroupSettings -Identity $group.Id
if (-Not $groupSettings)
{
$groupSettings = New-PnPMicrosoft365GroupSettings -Identity $group.Id -DisplayName "Group.Unified.Guest" -TemplateId "08d542b9-071f-4e16-94b0-74abb372e3d9" -Values @{"AllowToAddGuests"=$allowToAddGuests}
}
if (($groupSettings.Values | Where-Object { $_.Name -eq "AllowToAddGuests"}).Value.ToString() -ne $allowToAddGuests)
{
$groupSettings = Set-PnPMicrosoft365GroupSettings -Identity $groupSettings.ID -Group $group.Id -Values @{"AllowToAddGuests"=$allowToAddGuests}
}
#retrieving the details to ensure the settings are applied
$groupSettings = Get-PnPMicrosoft365GroupSettings -Identity $group.Id
$allowToAddGuestsValue = ($groupSettings.Values | Where-Object { $_.Name -eq "AllowToAddGuests"}).Value.ToString()
[PSCustomObject]@{
id = $group.Id
Description = $group.Description
DisplayName = $group.DisplayName
m365GroupAllowToAddGuests = $allowToAddGuestsValue ?? "Default"
}
}
$report |select * |Export-Csv $outputPath -NoTypeInformation -Append
Disconnect-PnPOnline
Check out the PnP PowerShell to learn more at: https://aka.ms/pnp/powershell
The way you login into PnP PowerShell has changed please read PnP Management Shell EntraID app is deleted : what should I do ?
Source Credit
Sample first appeared on Prevent Guests from Being Added to a Specific Microsoft 365 Group or Microsoft Teams team using PnP PowerShell
Contributors
Author(s) |
---|
Reshmee Auckloo |
Disclaimer
THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.