Wednesday, October 25, 2017

Adding Custom Action to SharePoint Online site

In this post, I'm providing the SPO powershell script which you can run from SPO management shell to add a new custom action to specific site.

You can use this script to render scripts on specific pages inside a site and  there by add any new options to users/ hide any option from end users.

Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "c:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
# Authenticate with the SharePoint site.
$actionName = "EM_SPO_JOSPODELWEB_JS_Injection"
$actionType = "ScriptLink"
$actionSourceFile =""
$siteUrl = Read-Host -Prompt "Enter web url:"
$username = Read-Host -Prompt "Enter Username:"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
# SharePoint Online
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$ctx.Credentials = $credentials
$rootWeb = $ctx.Web
$actions = $rootWeb.get_userCustomActions()
$actionsToDelete = @()
foreach($action in $actions)
if($action.get_description() -eq $actionName -and $action.get_location() -eq $actionType) {
Write-Host "Action found:" $action.get_description() -foregroundcolor white -backgroundcolor Green
$actionsToDelete += $action
foreach($actionToDelete in $actionsToDelete) {
Write-Host "Action deleted" -foregroundcolor white -backgroundcolor Green
Write-Host "Installing action"  -foregroundcolor white -backgroundcolor Green
$newAction = $actions.add();
$scriptBlock = 'var headIDDetails = document.getElementsByTagName("head")[0];var newScriptDetails = document.createElement("script");newScriptDetails.type = "text/javascript";newScriptDetails.src="';
$scriptBlock += $actionSourceFile + '?ver=' + (Get-Date) ;
$scriptBlock += '";headIDDetails.appendChild(newScriptDetails);';
Write-Host "Action" $newAction.Description "installed" -foregroundcolor white -backgroundcolor Green