I am developing a script to create/update group/team sites from a SharePoint list. I have everything working, but I am struggling big time with authentication.

I use

Connect-PnPOnline -Url https://client.sharepoint.com/sites/testclientsite -UseWebLogin -Scopes "Group.ReadWrite.All","Directory.Read.All"

In order to Apply-PnPProvisioningTemplate.

Anytime I am switching from the list and the newly created site to apply the template, I use

Connect-PnPOnline -Url https://client.sharepoint.com/sites/sharepointlist -UseWebLogin

To connect to SP List of clients

Connect-PnPOnline -Url https://client.sharepoint.com/sites/newsite -UseWebLogin

To connect to new site to apply template.

This works amazing through the first one or two sites, then I receive a

Apply-PnPProvisioningTemplate : The remote server returned an error: (403) Forbidden.

It is somewhat random. Sometimes it will make it through one or two sites. I have also had it work through 8 or so sites before it errors out. I am assuming it has something to do with the token expiring, but I am not positive. Any help would be appreciated.


I use 'service account' to do this instead of using UseWebLogin each time.

Hope it helps you.

#region Variables 
$Username = "user@tenant.onmicrosoft.com" 
$Password = "password" 
$siteURL = "https://tenant.sharepoint.com/sites/wiki" 

#endregion Variables

#region Credentials 
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force 
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass) 
#endregion Credentials

Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials

Apply-PnPProvisioningTemplate -Path "C:\Lee\Script\template.xml"

Thanks for the response, but I figured out my issue. When I created the group, I was not giving enough time to create the SP site for the group.Since the site has not been created yet, I get a 403. I just put a "pause"

Start-Sleep -Seconds 180

The pause solved my issue and allowed me to use -useweblogin


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.