Skip to content

Instantly share code, notes, and snippets.

@vgrem
Created November 2, 2016 10:24
Show Gist options
  • Select an option

  • Save vgrem/3fc5a6f9b07334362a2be5a5354cdce7 to your computer and use it in GitHub Desktop.

Select an option

Save vgrem/3fc5a6f9b07334362a2be5a5354cdce7 to your computer and use it in GitHub Desktop.
Register Google Analytics in SharePoint 2010/2013 site
param(
[string]$Url,
[string]$UserName,
[string]$Password,
[string]$Domain,
[string]$Code
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
<#
.SYNOPSIS
Activate Google Analytics
.DESCRIPTION
Activate Google Analytics in SharePoint On/Premise site
.EXAMPLE
.\Activate-GoogleAnalytics.ps1 -Url "https://tenant-public.sharepoint.com" -UserName "[email protected]" -Password "password" -Code "Tracking code"
#>
Function Activate-GoogleAnalytics([Microsoft.SharePoint.Client.ClientContext]$Context,[string]$TrackingCode)
{
$sequenceNo = 1480
#Insert your Tracking code here or specify valid Tracking ID
Add-ScriptLinkAction -Context $Context -ScriptBlock $TrackingCode -Sequence $sequenceNo
}
Function Add-ScriptLinkAction([Microsoft.SharePoint.Client.ClientContext]$Context,[string]$ScriptSrc,[string]$ScriptBlock, [int]$Sequence)
{
$actions = Get-ActionBySequence -Context $Context -Sequence $sequenceNo
$actions | ForEach-Object { Delete-Action -UserCustomAction $_ }
$action = $Context.Site.UserCustomActions.Add();
$action.Location = "ScriptLink"
if($ScriptSrc) {
$action.ScriptSrc = $ScriptSrc
}
if($ScriptBlock) {
$action.ScriptBlock = $ScriptBlock
}
$action.Sequence = $Sequence
$action.Update()
$Context.ExecuteQuery()
}
Function Get-ActionBySequence([Microsoft.SharePoint.Client.ClientContext]$Context,[int]$Sequence)
{
$customActions = $Context.Site.UserCustomActions
$Context.Load($customActions)
$Context.ExecuteQuery()
$customActions | where { $_.Sequence -eq $Sequence }
}
Function Delete-Action([Microsoft.SharePoint.Client.UserCustomAction]$UserCustomAction)
{
$Context = $UserCustomAction.Context
$UserCustomAction.DeleteObject()
$Context.ExecuteQuery()
}
Function Get-Context([string]$Url,[string]$UserName,[string]$Password,[string]$Domain)
{
$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$context.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password,$Domain)
return $context
}
#Usage
$context = Get-Context -Url $Url -UserName $UserName -Password $Password -Domain $Domain
Activate-GoogleAnalytics -Context $context -TrackingCode $Code
$context.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment