Adventures in PowerShell dot sourcing

As my company has started our journey to Office 365, we have had to go back and update a lot of our daily checks, scripts, and automations we put in place for user accounts. As a specific example we have a disable user script that performs various actions on a user’s mailbox depending on the wishes of the manager of said user. Depending on where the mailbox is located (on premises or in the cloud), we need to use either the set-mailbox or set-remotemailbox commands. In order support both scenarios in our existing scripts we leveraged dot sourcing to store the needed commands per mailbox type to the same variables used throughout the script. So that when we need to perform those mailbox actions, we don’t need to add a separate if or case statement for each action for the location of the mailbox. We instead leverage the variable holding the command via dot sourcing. The snippet below shows that we use the msExchRemoteRecipientType attribute of the user to determine the location of the user mailbox, and then save the appropriate commands to the matching variables.

        #Checking which Set-*mailbox command to use depending on the user is on prem or in the cloud
        if ($FoundAccount.msExchRemoteRecipientType -ne $NULL) {
            Write-Verbose "$UserAccount : Has a remote mailbox, using *-remotemailbox for all Exchange tasks"
            $SetMBXCommand = "Set-RemoteMailbox"
            $GetMBXCommand = "Get-RemoteMailbox"
            $DisableMBXCommand = "Disable-RemoteMailbox"
        }#if ($FoundAccount.msExchRemoteRecipientType -ne $NULL) {
        Else {
            Write-Verbose "$UserAccount : Has a local mailbox, using *-mailbox for all Exchange tasks"
            $SetMBXCommand = "Set-Mailbox"
            $GetMBXCommand = "Get-Mailbox"
            $DisableMBXCommand = "Disable-Mailbox"
        }#Else

When performing an action on the user mailbox we do source the variable for the command, which will expand the variable and treat it as the command store in the variable.

.$DisableMBXCommand $UserAccount -ErrorAction Stop -Confirm:$FALSE

About mell9185

IT proffesional. Tech, video game, anime, and punk aficionado.
This entry was posted in Exchange, Office 365, PowerShell. Bookmark the permalink.

Leave a Reply