Author Posts

July 19, 2016 at 1:11 pm

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?

July 19, 2016 at 1:57 pm

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
    }

}

September 22, 2017 at 5:50 pm

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):

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