set-calendar-perms/set-calendar-perms.ps1
2023-08-30 13:40:05 -06:00

62 lines
2.9 KiB
PowerShell

$TenantID = '538b9b1c-23fa-4102-b36e-a4d83fc9c4c1'
$ClientID = '6914cac7-e824-44e2-94af-1d5165121a11'
$CertThumb = '190ee98caf1003ef10fbfc05ded771f5940ab837'
$DefaultUserID = 'RGVmYXVsdA==' # I think this is equivalent to the "default" group in previous Calendars.
$365SKU = @('O365_BUSINESS_ESSENTIALS', 'O365_BUSINESS_PREMIUM', 'EXCHANGESTANDARD') # Licenses with mailboxes
$GroupsToIgnore = '^MPE Office Managers$|^CEO|Accounting$|^HR$' #Regex Format, match DisplayName
$GroupIDtoIgnore = Get-MgGroup -all -ConsistencyLevel eventual | where DisplayName -Match $GroupsToIgnore
$specialusersToIgnore = '#EXT#@mpe' #RegEx Format please
$specialusersToIgnore_IDs = @() # used to revert accidental changes to the permissions.
$upnToAdd = ''
$usersToIgnore = ''
# extract users from groups, merge with users to ignore.
$usersToIgnore = $specialusersToIgnore
foreach ($group in $GroupIDtoIgnore) {
$memberIDs = Get-MgGroupMember -GroupId $group.Id
foreach ($member in $memberIDs) {
$upnToAdd = Get-MgUser -UserId $member.Id
$specialusersToIgnore_IDs += $upnToAdd #adds for later usage
$usersToIgnore = $usersToIgnore + '|^' + $upnToAdd.UserPrincipalName + '$'
}
}
# Get full user list, then remove anything in $usersToIgnore variable. This should remove any guest accounts, as well as anyone in the $GroupsToIgnore
$users = get-mguser -all -Sort displayname | Where-Object UserPrincipalName -NotMatch $usersToIgnore
# $specialusersToIgnore_IDs = $specialusersToIgnore_IDs | sort -Unique -Descending #clears duplicates
#loop through all users in $users to set permissions to "read".
foreach ($user in $users) {
$UserLicense = get-mguserlicensedetail -UserId $user.id | where SkuPartNumber -in $365SKU # Only need to look at calendar perms if the user has a valid license. Returns Null / False if there's no match
if ($UserLicense) {
$currentPerms = Get-MgUserCalendarPermission -UserId $user.id
if ($currentPerms.Role -eq 'read' -and $currentPerms.id -eq $DefaultUserID) {
Write-Host -ForegroundColor blue Checked $($user.displayname)...
}
else {
Write-Host -ForegroundColor green Setting permission for $($user.displayname)...
Update-MgUserCalendarPermission -UserId $user.id -Role read -CalendarPermissionId $DefaultUserID
}
}
}
# Loop through ignored users in $specialusersToIgnore_ID's array, and reset Perms to "default"
foreach ($spec_id in $specialusersToIgnore_IDs) {
$currentPerms = Get-MgUserCalendarPermission -UserId $spec_id.Id
if ($currentPerms.Role -eq 'read' -and $currentPerms.id -eq $DefaultUserID) {
Write-Host -ForegroundColor Magenta Correcting $($spec_id.DisplayName)...
Update-MgUserCalendarPermission -UserId $spec_id.id -Role freeBusyRead -CalendarPermissionId $DefaultUserID
}
else {
}
}
Disconnect-MgGraph