Using PowerShell to Add WebPart to SharePoint Page via CSOM in Office 365


This time, I was supposed to add a webpart to SharePoint Online page programmatically.

It depends on our requirements, but we could use JavaScript or other Client Object Model libraries to add a web part to SharePoint page. My advice is, even if your requirements guide you to write PowerShell script, try to use Client Object Model instead Server Object Model, whenever possible.


Let’s share the code to add a Content Editor webpart to a SharePoint page:

Good to know

While I was developing this program, I found a problem with the format of XML. Specifically this problem:

The file you imported is not valid. Verify that the file is a Web Part description file (.webpart or .dwp) and that it contains well-formed XML. $wp = $webpartManager.ImportWebPart($WebPartXml.OuterXml)

Using PowerShell is really important consider the type of the variables we are using, in my case I was trying to ImportWebPart using a PowerShell variable called $WebPartXml, but the real XML object (as string) that ImportWebPart function expects is $WebPartXml.OuterXml.


Lot of thanks to my friend Benja for helping on that!


Author: José Quinto
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.