Exchange Online: Capturing Error Variable in Restricted Language Mode

This topic contains 2 replies, has 2 voices, and was last updated by  Jeff Brown 8 months ago.

  • Author
  • #47457

    Richard Diphoorn

    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        :

    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

    Richard Diphoorn

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

    if ( $User ) {
        Try {
            $user | Add-MailboxPermission -AccessRights FullAccess -User $SecurityGroup -InheritanceType All -AutoMapping:$false
        Catch {
            $Warn = $_.Exception.Message
  • #80398

    Jeff Brown

    I had to log in and thank you for coming back and posting the solution. I was running into the same thing with a Skype for Business Online cmdlet. -ErrorVariable was not working, and neither was -ErrorAction Stop in my try/catch block. Setting the preference beforehand fixed it (using Write-Host for brevity):

        # Set the telephone number for the user
        $ErrorActionPreference = "STOP"
        Set-CsOnlineVoiceUser -Identity $User -TelephoneNumber $TelephoneNumber -LocationID $LocationID -WarningAction SilentlyContinue
        Write-Host "ERROR: $_"

You must be logged in to reply to this topic.