Share via

PowerShell Script $exception not working

Anonymous
2023-11-14T16:57:54.8933333+00:00

I have a script as follows but I need to run it against domain A and then against domain B and not a UserPrincipal name it works with $Exception = @("@A-DOMAIN.org.uk", "@B-DOMAIN.org.uk") The script runs against domain A and B simultaneously with no issues.

But not using $Exception = @("@A-DOMAIN.org.uk") or $Exception = @("@B-DOMAIN.org.uk") how do I correct this the full script is below as I am new to this can anyone point out my mistakes

<#
    .SYNOPSIS
    PrepareAndSetDefaultCalendarPermissionsForAllUsers.ps1

    .DESCRIPTION
    Set default calendar permissions for all user mailboxes including exception for users.

    The script works for:
    -Exchange On-Premises (Run Exchange Management Shell)
    -Exchange Online (Connect to Exchange Online PowerShell)

    .LINK
    # Script Exclusions

    .NOTES
    # Exclude users that you don’t want the script to run against. Add them in line 36, 37, 38. If you don’t need this feature, comment out lines 36, 37, 38, 53, 54, 55, 56 and 80.
    # Calendars are not always set in the English language. For example, in The Netherlands, it’s named Agenda. The script will check for the calendar names defined in line 44.
    # Change permission that you want to set for all the users in line 39.
    # Note: The -WhatIf parameter is added in the script on line 66. If you run the script, nothing will happen in the environment. Instead, you get an output showing what will happen.
   
    .CHANGELOG
    # Line 36, 37, 38 Option enabled
    # -WhatIf parameter Active
#>

# Start transcript
Start-Transcript -Path "C:\temp\Set-DefCalPermissions01.log" -Append

# Set scope to entire forest. Cmdlet only available for Exchange on-premises.
#Set-ADServerSettings -ViewEntireForest $true

# Get all user mailboxes
$Users = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox

# Users exception (add the UserPrincipalName)
# $Exception = @("*@A-DOMAIN.org.uk")
# $Exception = @("*@B-DOMAIN.org.uk")
# $Exception = @("******@A-DOMAIN.org.uk", "******@B-DOMAIN.org.uk")

# Permissions
$Permission = "LimitedDetails"

# Calendar name languages
$FolderCalendars = @("Agenda", "Calendar", "Calendrier", "Kalender", "日历")

# Loop through each user
foreach ($User in $Users) {

    # Get calendar in every user mailbox
    $Calendars = (Get-MailboxFolderStatistics $User.UserPrincipalName -FolderScope Calendar)

    # Leave permissions if user is exception
    # if ($Exception -Contains ($User.UserPrincipalName)) {
       # Write-Host "$User is an exception, don't touch permissions" -ForegroundColor Red
    # }
    # else {

        # Loop through each user calendar
        foreach ($Calendar in $Calendars) {
            $CalendarName = $Calendar.Name

            # Check if calendar exist
            if ($FolderCalendars -Contains $CalendarName) {
                $Cal = "$($User.UserPrincipalName):\$CalendarName"
                $CurrentMailFolderPermission = Get-MailboxFolderPermission -Identity $Cal -User Default
                
                # Set calendar permission / Remove -WhatIf parameter after testing
                Set-MailboxFolderPermission -Identity $Cal -User Default -AccessRights $Permission -WarningAction:SilentlyContinue -WhatIf
                
                # Write output
                if ($CurrentMailFolderPermission.AccessRights -eq "$Permission") {
                    Write-Host $User.DisplayName already has the permission $CurrentMailFolderPermission.AccessRights -ForegroundColor Yellow
                }
                else {
                    Write-Host $User.DisplayName added permissions $Permission -ForegroundColor Green
                }
            }
        }
    }
# }

Stop-Transcript
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Rich Matheisen 48,116 Reputation points
2023-11-15T03:04:50.91+00:00

Here's an example of some code to verify that all exclusions have the same format. After determining exclusions consistency, it creates constructs a string from the users UPN that matches the examples in the $Exclusions variable.

$user = [PSCustomObject]@{UserPrincipalName='******@A-DOMAIN.org.uk'}

# setermine the pattern used in the exclusions list
# all exclusions must be of the same type
$MatchDomain = 0                        # 0=no determination, 1=domain, 2=@domain, 3=*@domain, 4=full UPN
#$Exceptions = @("@A-DOMAIN.org.uk")
$Exceptions = @("A-DOMAIN.org.uk","*@domain.com")
ForEach ($Exception in $Exceptions){
    $pieces = $Exception -split "@"
    if ($pieces.count -eq 1){
        if($MatchDomain -eq 0 -OR $MatchDomain -eq 1){
            $MatchDomain = 1
        }
        else{
            Throw "Exceptions list is not consistent"
        }
    }
    elseif ($pieces.count -eq 2){
        if ($pieces[0] -eq '*'){
            if ($MatchDomain -eq 0 -OR $MatchDomain -eq 3){
                $MatchDomain = 3
            }
            else{
                Throw "Exceptions list is not consistent"
            }
        }
        elseif($pieces[0].length -eq 0){
            if ($MatchDomain -eq 0 -OR $MatchDomain -eq 2){
                $MatchDomain = 2
            }
            else{
                Throw "Exceptions list is not consistent"
            }
        }
        else{
            if ($MatchDomain -eq 0 -OR $MatchDomain -eq 4){
                $MatchDomain = 4
            }
            else{
                Throw "Exceptions list is not consistent"
            }
        }
    }
    else{
        Throw "Exceptions list is not consistent"
    }
}

# build a string based on the exclusion pattern
$x = ""
Switch ($MatchDomain){
    1   {$x = ($user.UserPrincipalName -split "@")[1]; break}           #  domain
    2   {$x = '@' + ($user.UserPrincipalName -split "@")[1]; break}     # @domain
    3   {$x = '*@' + ($user.UserPrincipalName -split "@")[1]; break}    # *@domain
    4   {$x = $user.UserPrincipalName; break}                           # user@domain
    Default {$x = $user.UserPrincipalName; break}                       # in case of empty $Exclusions
}
if ($Exceptions -Contains $x) {
    Write-Host "$($user.UserPrincipalName) is an exception, don't touch permissions" -ForegroundColor Red
}

EDIT: Needed a "Default" condition for the Switch to deal with an empty $Exceptions list.

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2023-11-14T21:11:33.21+00:00

    "******@A-DOMAIN.org.uk" is a UPN, but "A-DOMAIN.org.uk" is only a part of a UPN.

    If your intention is to exclude the mailboxes from certain domains then the "$Exception" variable would have to contain only the domain portion of the UPNs. What you have in the $Exceptions variable are either substring matches (usable with the "-like" and "-notlike" operators) or regular expressions usable with the "-match" operator. (And, BTW, your textual description omits the asterisk, but the commented code contains the asterisk).

    To make this work with both the full UPN and the domain-only, you'll have to add a bit of decision-making code to distinguish between the cases. You might want to throw in some consistency checking to verify that all the names in $Exceptions are of the same sort. Don't forget to check for all '*****@domain.com' or all '@domain.xxx', or all '@domain.xxx' or all 'domain.xxx'.

    Before you look to see if the user (or its domain) is in the exclusions it would probably be easier to put the appropriate part of the users UPN into a new variable and use that in your "-contains" clause.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.