Home > Back-end >  Variable reference is invalid
Variable reference is invalid

Time:04-02

Can anyone help me with this issue, I haven't been able to find anything related to this.

Here's my script:

#Connect to Exchange PowerShell Online
Connect-ExchangeOnline -UserPrincipalName [email protected]

$repeatX = Read-Host -Prompt 'How many email to update?'
        Write-Host "Configuring default calendar permissions..."

        for($i = 1; $i -le $repeatX; $i  ) {
        $userPrincipalName = Read-Host -Prompt 'Enter email address'

do {
                $type=Read-Host ""`n============= What is the country?=============="
    1 - France
    2 - United States
    3 - Hong Kong SAR
    4 - United Kingdom
    Please choose with numbers"
                Write-Host "==================================================="
                Switch ($type){
                1 {$country="France"}
                2 {$country="United States"}
                3 {$country="Hong Kong SAR"}
                4 {$country="United Kingdom"}
                }
            } until (($country -eq 'France') -or ($country -eq 'United States') -or ($country -eq 'Hong Kong SAR') -or ($country -eq 'United Kingdom'))
            
            $country
              
            if ($country -eq 'United States') -or ($country -eq 'Hong Kong SAR') -or ($country -eq 'United Kingdom') {
                Set-MailboxFolderPermission $userPrincipalName:\Calendar -user Default -accessrights LimitedDetails
                Set-CalendarProcessing -Identity $userPrincipalName -AddOrganizerToSubject $true -DeleteComments $false -DeleteSubject $false
                }
            
                elseif($country -eq 'France') {
                Set-MailboxFolderPermission $userPrincipalName:\Calendrier -user Default -accessrights LimitedDetails
                Set-CalendarProcessing -Identity $userPrincipalName -AddOrganizerToSubject $true -DeleteComments $false -DeleteSubject $false
                }

}

Here's the part of the code which is having an issue: https://i.stack.imgur.com/WU4z0.png

And the error message that is roughly translated by myself so it might not be accurate.

"Variable reference is not valid. ":" was not followed by a valid variable name character"

CodePudding user response:

PowerShell variable expressions can include : to separate scope modifiers or path roots, so PowerShell attempts to include it as part of the variable name when you do $userprincipalName:\Calendar.

To prevent that, use {} to qualify the boundaries of the variable name and PowerShell will interpret the rest of the string argument as just that, a string literal, eg.:

Set-MailboxFolderPermission ${userPrincipalName}:\Calendar -user Default -accessrights LimitedDetails

Repeat for all instance of ${userPrincipalName}:\Calendar and the error will go away.

  • Related