Office 365 – Apply-PnPProvisioningTemplate : Exception has been thrown by the target of an invocation.

Quite a while back I experienced the following error generated by the Apply-PnPProvisioningTemplate Cmdlet.

Exception has been thrown by the target of an invocation.

Today I received the same error while I tried to apply PnP Templates to a site that I just created.OfficeDev/PnP

Maybe quite a basic mistake to make to create a new site and then change a few more things within the site and then when the PnP tmeplate is applied the ClientContext object is out of date and the above error is generated.

So to create a new site I’m first creating a new site after I checked that the site doesn’t already exist.

newWeb = web.GetWeb(Url);
if (newWeb == null)
WebCreationInformation newWebInfo = new Microsoft.SharePoint.Client.WebCreationInformation();
newWebInfo.WebTemplate = provisioningTemplate.BaseSiteTemplate;
newWebInfo.Description = provisioningTemplate.Description;
newWebInfo.Title = Title;
newWebInfo.Url = Url;
newWebInfo.Language = 1033;
newWeb = web.Webs.Add(newWebInfo);
ctx.Load(newWeb, w => w.Title);


Then a couple of other things are done to the site. with functions/methods that use their own client context (making my above ctx out of sync)

When running the following to apply the template the Exception is thrown:

newWeb.ApplyProvisioningTemplate(provisioningTemplate, provisioningInfo);

To solve this problem I created a new context and create a new web object from this new context:

ClientContext newWebCtx = new ClientContext(ctx.Web.Url + “/” + Url);

newWebCtx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(username, securePassword);
Web newApplyTemplateWWeb = newWebCtx.Web;
ProvisioningTemplateApplyingInformation provisioningInfo = new ProvisioningTemplateApplyingInformation();
newWebCtx.Web.ApplyProvisioningTemplate(provisioningTemplate, provisioningInfo);




Please leave a comment or feedback

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.