Here is the script from this blog for your reference:
Ensure that latest version of AzureAD and Teams modules are installed
Uninstall-Module AzureADPreview
Install-Module AzureADPreview
Install-Module MicrosoftTeams
#Admin user credentials
$Username = "<admin user>@tenant.onmicrosoft.com"
$passwd = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username,$passwd
#Connecting to AAD
Connect-AzureAD -Credential $cred
#Connecting to MS Teams
Connect-MicrosoftTeams -Credential $cred
#Connecting to Exchange Online
$Session = new-pssession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
#Getting all the O365 Groups
$0365Groups = Get-UnifiedGroup -ResultSize Unlimited
foreach($0365Group in $0365Groups)
{
try
{
#Check if the Channel exists. This line will throw an exception if the group is not associated with a team.
#This is to ensure that we are disabling external access only for those groups which have teams associated.
$teamChannel = Get-TeamChannel -GroupId $0365Group.ExternalDirectoryObjectId
#Check if the property exists
$GroupSettings = Get-AzureADObjectSetting -TargetType Groups -TargetObjectId $0365Group.ExternalDirectoryObjectId
if($GroupSettings)
{
$GroupSettings["AllowToAddGuests"] = $FALSE
#Updating the Property to restrict adding Guest User
Set-AzureADObjectSetting -Id $GroupSettings.Id -DirectorySetting $GroupSettings -TargetObjectId $0365Group.ExternalDirectoryObjectId -TargetType Groups
Write-Host "Updated for " $0365Group.DisplayName -ForegroundColor Green
}
else
{
$template = Get-AzureADDirectorySettingTemplate | ? {$_.displayname -eq "group.unified.guest"}
$settingsCopy = $template.CreateDirectorySetting()
$settingsCopy["AllowToAddGuests"]=$FALSE
#Creating the Property and setting the value to restrict adding Guest User
New-AzureADObjectSetting -TargetType Groups -TargetObjectId $0365Group.ExternalDirectoryObjectId -DirectorySetting $settingsCopy
Write-Host "Updated for " $0365Group.DisplayName -ForegroundColor Green
}
}
catch
{
Write-Host ($0365Group.DisplayName + " is not a Team")
}
Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.