Categories
SharePoint

Creating SharePoint alerts via CSOM

I’m posting this as a useful reminder. It outlines how alerts can now be created via CSOM. New SharePoint CSOM version released for SharePoint Online – February 2017 The included code sample is in C#, but I’ve translated it to PowerShell – which suits my administrative needs better.

I’m posting this as a useful reminder. It outlines how alerts can now be created via CSOM.

New SharePoint CSOM version released for SharePoint Online – February 2017

The included code sample is in C#, but I’ve translated it to PowerShell – which suits my administrative needs better.

[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.SharePoint.Client" ) | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.SharePoint.Client.Runtime" ) | Out-Null


# Set variables
$path = "C:\Temp\Usernames.txt"

$url = "https://xxxxxx.sharepoint.com/sites/help"

$list = "My List"

$title = "$list (Auto-subscribed)"


# Prompt the administrator to log in
$credential = Get-Credential -Credential $null


# Create a connection to SharePoint Online
$context = New-Object Microsoft.SharePoint.Client.ClientContext( $url )
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials( $credential.UserName, $credential.Password )


# Retrieve the targeted web
$web = $context.Web

$context.Load( $web )
$context.ExecuteQuery()


# Loop through the provided usernames and create a new alert for each one
$usernames = Get-Content -Path $path

foreach ( $username in $usernames )
{
    $user = $context.Web.EnsureUser( $username )

    $alert = New-Object Microsoft.SharePoint.Client.AlertCreationInformation
    $alert.List = $context.Web.Lists.GetByTitle( $list )
    $alert.AlertFrequency = [Microsoft.SharePoint.Client.AlertFrequency]::Daily
    $alert.AlertTime = ( Get-Date ).AddDays( 1 )
    $alert.AlertType = [Microsoft.SharePoint.Client.AlertType]::List
    $alert.AlwaysNotify = $false
    $alert.DeliveryChannels = [Microsoft.SharePoint.Client.AlertDeliveryChannel]::Email
    $alert.Status = [Microsoft.SharePoint.Client.AlertStatus]::On
    $alert.Title = $title
    $alert.User = $user
    $alert.EventType = [Microsoft.SharePoint.Client.AlertEventType]::All
    $alert.Filter = "1"

    $guid = $user.Alerts.Add( $alert )

    $user.Update()

    $context.ExecuteQuery()
}