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);
ctx.ExecuteQueryRetry();

}

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;
newWebCtx.Load(newWebCtx.Web);
newWebCtx.ExecuteQueryRetry();
ProvisioningTemplateApplyingInformation provisioningInfo = new ProvisioningTemplateApplyingInformation();
newWebCtx.Web.ApplyProvisioningTemplate(provisioningTemplate, provisioningInfo);


Discover more from SharePains

Subscribe to get the latest posts sent to your email.

Related Posts

Leave a Reply

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

Discover more from SharePains

Subscribe now to keep reading and get access to the full archive.

Continue reading