Exception calling "ExecuteQuery": Access denied for RequestAccessEmail

Deleted
Not applicable

Hello,

 

So, I've made a script to automate the creation of a Team with some fine tuning. One of these fine tuning is to set the Email for Access requests. This script works fine and I can see Access request email field is populated in the corresponding page on a Web browser.

 

Now, I would like to get a list of Email address of Access requests for all SPO sites and get the error message each and every time:

Exception calling "ExecuteQuery" with "0" argument(s): "Access denied. You do not have
permission to perform this action or access this resource."
At C:\Scripts\Update-TeamsOnProd.ps1:90 char:17
+                 $ctx.ExecuteQuery()
+                 ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServerUnauthorizedAccessException

 

Nevertheless, the email address is clearly there when you go:

https://My_Tenant.sharepoint.com/sites/Some_Site/_layouts/15/user.aspx

 

Here is my script:

#################
### Variables ###
#################

$OutputFile = "Some_Path.csv"
$Office365Username = "My_username"
$Office365Password = "My_Password"
$SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365Password -Force
$credential  = New-Object System.Management.Automation.PSCredential $Office365Username, $SecureOffice365Password


################################
### Connecting to everything ###
################################

## Removing existing ExO session ##
Get-PSSession | Remove-PSSession 

## Connecting to Office 365 ##
echo 'Connecting to Office 365'
Import-Module MsOnline
Connect-MsolService -Credential $credential

## Connecting to Exchange Online ##
echo 'Connecting to Exchange Online'
$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -AllowRedirection
Import-PSSession $ExchangeSession -DisableNameChecking | Out-Null

## Connecting to SharePoint Online ##
echo 'Connecting to SharePoint Online'
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
Connect-SPOService -Url https://My_Tenant-admin.sharepoint.com -credential $credential

## Asking credentials for CSOM ##
echo 'Getting credentials for CSOM'
$CtxCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Office365Username, $SecureOffice365Password)

 

############################################
### Populating the List with Teams infos ###
############################################


## Clearing the .csv ##
Clear-Content "Some_Path.csv"

## Preparing output file with headers ##
Out-File -FilePath $OutputFile -InputObject "Team Display Name,Team email address,Team creation date,Team last modification,Storage used,Access Req. Email manager,Owners email address" -Encoding UTF8 -append

## Parsing all SPO sites ##
$SPOSites = Get-SPOSite
Foreach ($SPOSite in $SPOSites) 
{     
    ## Filtering on active SPO sites ##
    if ($SPOSite.LockState -ne "NoAccess")
    {
        Connect-PnPOnline $SPOSite.Url –Credentials $credential
        $PnPSite = Get-PnPSite
        $PnPSite.Classification
        $PnPProperty = Get-PnPProperty -ClientObject $PnPSite -Property Classification

        ## Filtering on SPO sites flagged on Prod ##
        if ($PnPProperty -eq "Production")
        {
            ## Getting the o365 group based the SPO url ##
            $o365Group = Get-UnifiedGroup | Where-Object {$_.SharePointSiteUrl -eq $SPOSite.Url}
            echo $o365Group.SharePointSiteUrl

            ## Filtering on o365 groups with valid names ##
            if ([string]::IsNullOrWhiteSpace($o365Group.name))
            {}
            else
            {
                ## Getting 'Access Request email' owner ##
                $site = $SPOSite.url
                $ctx = New-Object Microsoft.SharePoint.Client.ClientContext("$site")
                $ctx.Credentials = $CtxCreds
                $ctx.Load($ctx.web)
                $ctx.Load($ctx.web.AllProperties)
                $ctx.web.Update()
                $ctx.ExecuteQuery()

                $AccessReq = $ctx.web.RequestAccessEmail

                ## Writing info on the .csv ##
                Out-File -FilePath $OutputFile -InputObject "$($o365Group.DisplayName),$($o365Group.PrimarySMTPAddress),$($o365Group.WhenCreated),$($o365Group.WhenChanged),$($SPOSite.StorageUsageCurrent) MB ,$($AccessReq)," -Encoding UTF8 -append -NoNewline
                
                ## Getting Teams owners ##
                $objTeamOwners = Get-UnifiedGroupLinks -Identity $o365Group.name -LinkType Owners
                
                Foreach ($objTeamOwner in $objTeamOwners) 
	            { 
    		        ## Writing Owners on the .csv
                    Out-File -FilePath $OutputFile -InputObject "$($objTeamOwner.PrimarySMTPAddress)  -  " -Encoding UTF8 -append -NoNewline
	            }
    
                Out-File -FilePath $OutputFile -InputObject "" -Encoding UTF8 -append 
            }
        }
    }
}

$CSV = Import-Csv $OutputFile
$CSV | Export-Excel "Some_Path.xlsx"

 

2 Replies
I think you are facing a common problem here: your Group is created but the linked SPO Site is not quite ready yet so that's the reason why you are getting an access denied message

Hello,

 

Thank you for your answer.

I'm not creating anything in that script, I'm just parsing through all teams with some filters (active sites, marked as on "Production", etc.) and trying to read the "Access request email" parameter from the SPO sites of the Team.