Exchange Online: Capturing Error Variable in Restricted Language Mode

This topic contains 1 reply, has 1 voice, and was last updated by Profile photo of Richard Diphoorn Richard Diphoorn 4 months, 2 weeks ago.

  • Author
    Posts
  • #47457
    Profile photo of Richard Diphoorn
    Richard Diphoorn
    Participant

    Hi folks, a question. When you connect to Exchange Online, import the session cmdlets, and trying to use the parameter -ErrorVariable with for example Add-MailboxPermission, this will not work. This is because the language mode is set to restricted in Exchange Online.

    For example:

    PS C:\> Get-Mailbox -Identity $user.UserPrincipalName | Add-MailboxPermission -AccessRights FullAccess -User $SecurityGroup -InheritanceType All -AutoMapping:$false -ErrorVariable Warn
    A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: $PSCulture, $PSUICulture, $true
    , $false, and  $null.
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : VariableReferenceNotSupportedInDataSection
        + PSComputerName        : outlook.office365.com
    

    I understand language modes, and I'm not really sure this is solvable without Microsoft changing something on their side. But, better to ask than to assume. Does someone has a clue how to capture the error in a variable in this situation?

  • #47461
    Profile photo of Richard Diphoorn
    Richard Diphoorn
    Participant

    To answer my own question, I solved this with a Try/Catch construct like this:

    if ( $User ) {
        
        Try {
            $ErrorActionPreference='Stop'
            $user | Add-MailboxPermission -AccessRights FullAccess -User $SecurityGroup -InheritanceType All -AutoMapping:$false
        }
        
        Catch {
            $Warn = $_.Exception.Message
        }
    
    }
    

You must be logged in to reply to this topic.