Showing posts with label JS Link. Show all posts
Showing posts with label JS Link. Show all posts

Monday, May 22, 2017

Powershell to add JS Link in SharePoint Online

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_ZIN_JS_Injection"
$actionType = "ScriptLink"
$actionSourceFile ="https://cdnpath/Detailsview.js"


$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
$ctx.Load($rootWeb)
$actions = $rootWeb.get_userCustomActions()
$ctx.Load($actions)
$ctx.ExecuteQuery()
if($actions)
{
$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) {
    $actionToDelete.deleteObject()
Write-Host "Action deleted" -foregroundcolor white -backgroundcolor Green
}
$ctx.ExecuteQuery()
}


Write-Host "Installing action"  -foregroundcolor white -backgroundcolor Green
$newAction = $actions.add();
$newAction.set_description($actionName);
$newAction.set_location('ScriptLink');
$scriptBlock = 'var headID = document.getElementsByTagName("head")[0];var newScript = document.createElement("script");newScript.type = "text/javascript";newScript.src="';
$scriptBlock += $actionSourceFile + '?ver=' + (Get-Date);
$scriptBlock += '";headID.appendChild(newScript);';
$newAction.set_scriptBlock($scriptBlock);
$newAction.update();
$ctx.ExecuteQuery();

Write-Host "Action" $newAction.Description "installed" -foregroundcolor white -backgroundcolor Green