none
Adding script editor webpart to wiki page in csom powershell RRS feed

  • Question

  • Hi I'm trying to insert the MS Script Editor webpart into wiki pages in Sharepoint Online, this is so I can insert some html and javascript into pages (adding it as content of the wiki page cause Sharepoint to strip out the javascript and alter the html).

    Ran across a script to do this and edited it a little. The script seems to execute fine however on the context ExecuteQuery call it keeps telling me the webpart is not well formed. I have done everything can think of, checked the file encoding, stripping the file down to minimum properties, altering the xml structure an number of ways before returning to the original but nothing works. I downloaded the webpart xml from the site settings > web part gallery and exported it but even that doesn't work.

    Here is the script output:

    Add the webpart to the Page

    Starting the Process to add the User WebPart to the Home Page
    Getting the page with the webpart we are going to modify
    Getting the page with the webpart we are going to modify:  /sites/NursingTest/carehome/AdminHome.aspx
    The page is checkout
    Getting the webparts from the page
    <?xml version="1.0" encoding="utf-8"?><webParts><webPart xmlns="http://schemas.microsoft.com/WebPart/v3"><metaData><type name="Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.ShareP
    oint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" /><importErrorMessage>Can't import webpart</importErrorMessage></metaData><data><properties><property name="Title" type="str
    ing">Bretts Web Part</property><property name="Description" type="string">My script editor</property><property name="ChromeType" type="chrometype">None</property></properties></data></webPart></webP
    arts>

    Errors found:

    Exception calling "ExecuteQuery" with "0" argument(s): "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."
    Checkin and Publish the Page
    The webpart has been added

    Here is the script:

    #Load SharePoint Client Assemblies 
    Try{
        Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll'
        Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
        Add-Type -Path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Publishing.dll'
    }
    
    catch {
        Throw "Unable to load SharePoint Client runtime"
    }
    
    
    # Change for your web URL
    $url = "https://x.sharepoint.com/sites/site"
    #$username = Read-Host -Prompt "Username"
    #$password = Read-Host -Prompt "Password" -AsSecureString
    
     $username = "admin@something.onmicrosoft.com"
     $password = "pass"
     $password = $(convertto-securestring $password -asplaintext -force)
    
    # set SharePoint Online credentials
    $SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
             
    # Creating client context object
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
    $context.credentials = $SPOCredentials
    
    function AddWebPartToPage ($ctx, $sitesURL) {
    
    	$pageRelativeUrl = "/wikilib/Home.aspx"
    	$wpZoneID = "Left"
    	$wpZoneOrder= 0
    
    
    	try{
    
    		Write-Host "Starting the Process to add the User WebPart to the Home Page" -ForegroundColor Yellow
    
    		#Adding the reference to the client libraries. Here I'm executing this for a SharePoint Server (and I'm referencing it from the SharePoint ISAPI directory, 
    		#but we could execute it from wherever we want, only need to copy the dlls and reference the path from here        
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
    		
    		Write-Host "Getting the page with the webpart we are going to modify" -ForegroundColor Green
    
    		#Using the params, build the page url
    		$pageUrl = $sitesURL + $pageRelativeUrl
    		Write-Host "Getting the page with the webpart we are going to modify: " $pageUrl -ForegroundColor Green
    
    		#Getting the page using the GetFileByServerRelativeURL and do the Checkout
    		#After that, we need to call the executeQuery to do the actions in the site
    		$page = $ctx.Web.GetFileByServerRelativeUrl($pageUrl);
    		$page.CheckOut()
    		$ctx.ExecuteQuery()
    		try{
    
    		#Get the webpart manager from the page, to handle the webparts
    		Write-Host "The page is checkout" -ForegroundColor Green
    		$webpartManager = $page.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);
    
    
    		#Load and execute the query to get the data in the webparts
    		Write-Host "Getting the webparts from the page" -ForegroundColor Green
    		$ctx.Load($webpartManager);
    		$ctx.ExecuteQuery();
    
    		#Import the webpart        
            $WebPartFilePath = "C:\Webparts\MSScriptEditorCut.webpart"
            [xml]$WebPartXml1 = get-content $WebPartFilePath
            Write-Host $WebPartXml1.OuterXml
            $SR = New-Object System.IO.StringReader($WebPartXml1.OuterXml)
            $XTR = New-Object System.Xml.XmlTextReader($SR)
            $WP = $webpartManager.ImportWebPart($XTR)
            Write-Host "Add the webpart to the Page" -ForegroundColor Green
            $webPartToAdd = $webpartManager.AddWebPart($WP.WebPart, $wpZoneID, $wpZoneOrder)
    
    		#Add the webpart to the page
                
    		$ctx.Load($webPartToAdd);
    		$ctx.ExecuteQuery()
    		}
    		catch{
    			Write-Host "Errors found:`n$_" -ForegroundColor Red
    
    		}
    		finally{
    			#CheckIn and Publish the Page
    			Write-Host "Checkin and Publish the Page" -ForegroundColor Green
    			$page.CheckIn("Add the User Profile WebPart", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
    			#$page.Publish("Add the User Profile WebPart")
    			$ctx.ExecuteQuery()
    
    			Write-Host "The webpart has been added" -ForegroundColor Yellow 
    			
    		}	
    
    	}
    	catch{
    		Write-Host "Errors found:`n$_" -ForegroundColor Red
    	}
    
    }
    
    ######################################
    # Set Add WebPart to Page Parameters #
    ######################################
    $relUrl = "/sites/sitename"
    AddWebPartToPage $context $relUrl


    Here is the xml for MSScriptEditorCut.webpart

    <?xml version="1.0" encoding="utf-8"?>
    <webParts>
    	<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    		<metaData>
    			<type name=
    "Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    			<importErrorMessage>Can't import webpart</importErrorMessage>
    		</metaData>
    		<data>
    			<properties>
    				<property name="Title" type="string">Bretts Web Part</property>
    				<property name="Description" type="string">My script editor</property>
    				<property name="ChromeType" type="chrometype">None</property>
    			</properties>
    		</data>
    	</webPart>
    </webParts>


    Here is another attempt

    <?xml version="1.0" encoding="utf-8" ?>
    <webParts>
    	<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    		<metaData>
    			<type name="Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
    			<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    		</metaData>
    		<data>
    			<properties>
    				<property name="ExportMode" type="exportmode">All</property>
    				<property name="HelpUrl" type="string" />
    				<property name="Hidden" type="bool">False</property>
    				<property name="Description" type="string">Allows authors to insert HTML snippets or scripts.</property>
    				<property name="Content" type="string">Hello</property>
    				<property name="CatalogIconImageUrl" type="string" />
    				<property name="Title" type="string">Bretts Script editor</property>
    				<property name="AllowHide" type="bool">True</property>
    				<property name="AllowMinimize" type="bool">True</property>
    				<property name="AllowZoneChange" type="bool">True</property>
    				<property name="TitleUrl" type="string" />
    				<property name="ChromeType" type="chrometype">None</property>
    				<property name="AllowConnect" type="bool">True</property>
    				<property name="Width" type="unit" />
    				<property name="Height" type="unit" />
    				<property name="HelpMode" type="helpmode">Navigate</property>
    				<property name="AllowEdit" type="bool">True</property>
    				<property name="TitleIconImageUrl" type="string" />
    				<property name="Direction" type="direction">NotSet</property>
    				<property name="AllowClose" type="bool">True</property>
    				<property name="ChromeState" type="chromestate">Normal</property>
    			</properties>
    		</data>
    	</webPart>
    </webParts>

    Thanks

    Thursday, March 23, 2017 9:46 AM

Answers

  • Hi,

    We can use the following PowerShell script to add the script editor web part to a page.

    function AddWebPartToPage ($ctx, $sitesURL) {
    
    	$pageRelativeUrl = $sitesURL
    	$wpZoneID = "Left"
    	$wpZoneOrder= 0
    
    	$WebPartXml = [xml] "
    	<webParts>
    	  <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
    		<metaData>
    		  <type name='Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
    		  <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    		</metaData>
    		<data>
    		  <properties>
    			<property name='ExportMode' type='exportmode'>All</property>
    			<property name='HelpUrl' type='string' />
    			<property name='Hidden' type='bool'>False</property>
    			<property name='Description' type='string'>Allows authors to insert HTML snippets or scripts.</property>
    			<property name='Content' type='string'>&lt;script type='text/javascript'&gt;alert('Test Dennis');&lt;/script&gt;</property>
    			<property name='CatalogIconImageUrl' type='string' />
    			<property name='Title' type='string'>Script Editor</property>
    			<property name='AllowHide' type='bool'>True</property>
    			<property name='AllowMinimize' type='bool'>True</property>
    			<property name='AllowZoneChange' type='bool'>True</property>
    			<property name='TitleUrl' type='string' />
    			<property name='ChromeType' type='chrometype'>None</property>
    			<property name='AllowConnect' type='bool'>True</property>
    			<property name='Width' type='unit' />
    			<property name='Height' type='unit' />
    			<property name='HelpMode' type='helpmode'>Navigate</property>
    			<property name='AllowEdit' type='bool'>True</property>
    			<property name='TitleIconImageUrl' type='string' />
    			<property name='Direction' type='direction'>NotSet</property>
    			<property name='AllowClose' type='bool'>True</property>
    			<property name='ChromeState' type='chromestate'>Normal</property>
    		  </properties>
    		</data>
    	  </webPart>
    	</webParts>"
    		
    	try{
    
    		Write-Host "Starting the Process to add the User WebPart to the Home Page" -ForegroundColor Yellow
    
    		#Adding the reference to the client libraries. Here I'm executing this for a SharePoint Server (and I'm referencing it from the SharePoint ISAPI directory, 
    		#but we could execute it from wherever we want, only need to copy the dlls and reference the path from here        
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
    		
    		Write-Host "Getting the page with the webpart we are going to modify" -ForegroundColor Green
    
    		#Using the params, build the page url
    		$pageUrl = $pageRelativeUrl
    		Write-Host "Getting the page with the webpart we are going to modify: " $pageUrl -ForegroundColor Green
    
    		#Getting the page using the GetFileByServerRelativeURL and do the Checkout
    		#After that, we need to call the executeQuery to do the actions in the site
    		$page = $ctx.Web.GetFileByServerRelativeUrl($pageUrl)
    		$page.CheckOut()
    		$ctx.ExecuteQuery()
    		try{
    
    		#Get the webpart manager from the page, to handle the webparts
    		Write-Host "The page is checkout" -ForegroundColor Green
    		$webpartManager = $page.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);
    
    		Write-Host $WebPartXml.OuterXml
    
    		#Load and execute the query to get the data in the webparts
    		Write-Host "Getting the webparts from the page" -ForegroundColor Green
    		$ctx.Load($webpartManager);
    		$ctx.ExecuteQuery();
    
    		#Import the webpart
    		$wp = $webpartManager.ImportWebPart($WebPartXml.OuterXml)
    		
    
    		#Add the webpart to the page
    		Write-Host "Add the webpart to the Page" -ForegroundColor Green
    		$webPartToAdd = $webpartManager.AddWebPart($wp.WebPart, $wpZoneID, $wpZoneOrder)
                
    		$ctx.Load($webPartToAdd);
    		$ctx.ExecuteQuery()
    		}
    		catch{
    			Write-Host "Errors found:`n$_" -ForegroundColor Red
    
    		}
    		finally{
    			#CheckIn the Page
    			Write-Host "Checkin  the Page" -ForegroundColor Green
    			$page.CheckIn("Add the User Profile WebPart", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)			
    			$ctx.ExecuteQuery()
    
    			Write-Host "The webpart has been added" -ForegroundColor Yellow 			
    		}	
    
    	}
    	catch{
    		Write-Host "Errors found:`n$_" -ForegroundColor Red
    	}
    
    }
    
    Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
    Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
    $tenantAdmin = "xxx@xxx.onmicrosoft.com"
    $tenantAdminPassword = "xxx"
    $secureAdminPassword = $(convertto-securestring $tenantAdminPassword -asplaintext -force)
    $siteURL = "https://xxx.sharepoint.com/sites/dennis"
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL) 
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin, $secureAdminPassword)  
    $ctx.Credentials = $credentials
    
    ######################################
    # Set Add WebPart to Page Parameters #
    ######################################
    $relUrl = "/sites/dennis/SitePages/Home.aspx"
    AddWebPartToPage $ctx $relUrl

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by BrettLawless Friday, March 24, 2017 9:45 AM
    Friday, March 24, 2017 5:03 AM
    Moderator

All replies

  • Hi,

    We can use the following PowerShell script to add the script editor web part to a page.

    function AddWebPartToPage ($ctx, $sitesURL) {
    
    	$pageRelativeUrl = $sitesURL
    	$wpZoneID = "Left"
    	$wpZoneOrder= 0
    
    	$WebPartXml = [xml] "
    	<webParts>
    	  <webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>
    		<metaData>
    		  <type name='Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />
    		  <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    		</metaData>
    		<data>
    		  <properties>
    			<property name='ExportMode' type='exportmode'>All</property>
    			<property name='HelpUrl' type='string' />
    			<property name='Hidden' type='bool'>False</property>
    			<property name='Description' type='string'>Allows authors to insert HTML snippets or scripts.</property>
    			<property name='Content' type='string'>&lt;script type='text/javascript'&gt;alert('Test Dennis');&lt;/script&gt;</property>
    			<property name='CatalogIconImageUrl' type='string' />
    			<property name='Title' type='string'>Script Editor</property>
    			<property name='AllowHide' type='bool'>True</property>
    			<property name='AllowMinimize' type='bool'>True</property>
    			<property name='AllowZoneChange' type='bool'>True</property>
    			<property name='TitleUrl' type='string' />
    			<property name='ChromeType' type='chrometype'>None</property>
    			<property name='AllowConnect' type='bool'>True</property>
    			<property name='Width' type='unit' />
    			<property name='Height' type='unit' />
    			<property name='HelpMode' type='helpmode'>Navigate</property>
    			<property name='AllowEdit' type='bool'>True</property>
    			<property name='TitleIconImageUrl' type='string' />
    			<property name='Direction' type='direction'>NotSet</property>
    			<property name='AllowClose' type='bool'>True</property>
    			<property name='ChromeState' type='chromestate'>Normal</property>
    		  </properties>
    		</data>
    	  </webPart>
    	</webParts>"
    		
    	try{
    
    		Write-Host "Starting the Process to add the User WebPart to the Home Page" -ForegroundColor Yellow
    
    		#Adding the reference to the client libraries. Here I'm executing this for a SharePoint Server (and I'm referencing it from the SharePoint ISAPI directory, 
    		#but we could execute it from wherever we want, only need to copy the dlls and reference the path from here        
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
    		Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
    		
    		Write-Host "Getting the page with the webpart we are going to modify" -ForegroundColor Green
    
    		#Using the params, build the page url
    		$pageUrl = $pageRelativeUrl
    		Write-Host "Getting the page with the webpart we are going to modify: " $pageUrl -ForegroundColor Green
    
    		#Getting the page using the GetFileByServerRelativeURL and do the Checkout
    		#After that, we need to call the executeQuery to do the actions in the site
    		$page = $ctx.Web.GetFileByServerRelativeUrl($pageUrl)
    		$page.CheckOut()
    		$ctx.ExecuteQuery()
    		try{
    
    		#Get the webpart manager from the page, to handle the webparts
    		Write-Host "The page is checkout" -ForegroundColor Green
    		$webpartManager = $page.GetLimitedWebPartManager([Microsoft.Sharepoint.Client.WebParts.PersonalizationScope]::Shared);
    
    		Write-Host $WebPartXml.OuterXml
    
    		#Load and execute the query to get the data in the webparts
    		Write-Host "Getting the webparts from the page" -ForegroundColor Green
    		$ctx.Load($webpartManager);
    		$ctx.ExecuteQuery();
    
    		#Import the webpart
    		$wp = $webpartManager.ImportWebPart($WebPartXml.OuterXml)
    		
    
    		#Add the webpart to the page
    		Write-Host "Add the webpart to the Page" -ForegroundColor Green
    		$webPartToAdd = $webpartManager.AddWebPart($wp.WebPart, $wpZoneID, $wpZoneOrder)
                
    		$ctx.Load($webPartToAdd);
    		$ctx.ExecuteQuery()
    		}
    		catch{
    			Write-Host "Errors found:`n$_" -ForegroundColor Red
    
    		}
    		finally{
    			#CheckIn the Page
    			Write-Host "Checkin  the Page" -ForegroundColor Green
    			$page.CheckIn("Add the User Profile WebPart", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)			
    			$ctx.ExecuteQuery()
    
    			Write-Host "The webpart has been added" -ForegroundColor Yellow 			
    		}	
    
    	}
    	catch{
    		Write-Host "Errors found:`n$_" -ForegroundColor Red
    	}
    
    }
    
    Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll" 
    Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" 
    $tenantAdmin = "xxx@xxx.onmicrosoft.com"
    $tenantAdminPassword = "xxx"
    $secureAdminPassword = $(convertto-securestring $tenantAdminPassword -asplaintext -force)
    $siteURL = "https://xxx.sharepoint.com/sites/dennis"
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL) 
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin, $secureAdminPassword)  
    $ctx.Credentials = $credentials
    
    ######################################
    # Set Add WebPart to Page Parameters #
    ######################################
    $relUrl = "/sites/dennis/SitePages/Home.aspx"
    AddWebPartToPage $ctx $relUrl

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by BrettLawless Friday, March 24, 2017 9:45 AM
    Friday, March 24, 2017 5:03 AM
    Moderator
  • Thanks that works now, I'm still puzzled as to why loading the webpart in from a file has caused so much trouble. Will load in my html & scripts and append it to this script in the xml content section :)
    Friday, March 24, 2017 9:47 AM
  • Hi,

    If you want to add the HTML or script into the xml content section, please convert "<" to "&lt;" and convert ">" to "&gt;".

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    Sunday, March 26, 2017 1:36 AM
    Moderator