Public/Group.ps1
|
<# .SYNOPSIS Manages Microsoft 365 Groups. .DESCRIPTION This function allows you to create, delete, and update Microsoft 365 Groups. .PARAMETER Action The action to perform. Valid values are 'Create', 'Delete', 'Update'. .PARAMETER GroupId The ID of the group to manage. .PARAMETER GroupName The name of the group. .PARAMETER GroupAlias The alias of the group. .PARAMETER Members An array of user UPNs to add as members. .PARAMETER Owners An array of user UPNs to add as owners. .EXAMPLE Manage-O365Group -Action Create -GroupName 'My New Group' -GroupAlias 'mynewgroup' -Members 'user1@contoso.com', 'user2@contoso.com' -Owners 'admin@contoso.com' .NOTES You must be connected to the Microsoft Graph with the 'Group.ReadWrite.All' scope before running this function. #> function Manage-O365Group { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet('Create', 'Delete', 'Update')] [string]$Action, [string]$GroupId, [string]$GroupName, [string]$GroupAlias, [string[]]$Members, [string[]]$Owners ) switch ($Action) { 'Create' { Write-Verbose "Creating new group: $GroupName" $Group = New-MgGroup -DisplayName $GroupName -MailEnabled:$true -MailNickname $GroupAlias -GroupTypes 'Unified' if ($Members) { foreach ($Member in $Members) { $User = Get-MgUser -UserId $Member if ($User) { Add-MgGroupMember -GroupId $Group.Id -DirectoryObjectId $User.Id } } } if ($Owners) { foreach ($Owner in $Owners) { $User = Get-MgUser -UserId $Owner if ($User) { Add-MgGroupOwner -GroupId $Group.Id -DirectoryObjectId $User.Id } } } return $Group } 'Delete' { if (-not $GroupId) { Write-Warning "GroupId is required for the Delete action." return } Write-Verbose "Deleting group: $GroupId" Remove-MgGroup -GroupId $GroupId } 'Update' { if (-not $GroupId) { Write-Warning "GroupId is required for the Update action." return } Write-Verbose "Updating group: $GroupId" $Group = Get-MgGroup -GroupId $GroupId if ($GroupName) { Update-MgGroup -GroupId $GroupId -DisplayName $GroupName } if ($Members) { foreach ($Member in $Members) { $User = Get-MgUser -UserId $Member if ($User) { Add-MgGroupMember -GroupId $GroupId -DirectoryObjectId $User.Id } } } if ($Owners) { foreach ($Owner in $Owners) { $User = Get-MgUser -UserId $Owner if ($User) { Add-MgGroupOwner -GroupId $GroupId -DirectoryObjectId $User.Id } } } return Get-MgGroup -GroupId $GroupId } } } |