Exchange Online: Capturing Error Variable in Restricted Language Mode

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?

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


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: $_"