Add SharePoint remote event receivers using PowerShell

You can use the following PowerShell script to add a remote event receiver in SharePoint 2013/2016:

 

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"

#Site & context

$siteUrl = "https://siteurl/"

$listTitle = "listTitle"

 

$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)

$clientContext.Credentials = New-Object System.Net.NetworkCredential("domain\user", "pass")

 

function addListItemRemoteEventReceiver([Microsoft.SharePoint.Client.ClientContext]$context, [string]$listTitle,

[Microsoft.SharePoint.Client.EventReceiverType]$eventType, [Microsoft.SharePoint.Client.EventReceiverSynchronization]$synchronization,

[string]$receiverName, [string]$receiverUrl, [string]$receiverAssemblyName, [string]$receiverClassName)

{

$list = $context.Web.Lists.GetByTitle($listTitle);

$context.Load($list)

$eventReceivers = $list.EventReceivers

$context.Load($eventReceivers)

$context.ExecuteQuery()

 

$newRER = New-Object Microsoft.SharePoint.Client.EventReceiverDefinitionCreationInformation

$newRER.EventType = $eventType

$newRER.ReceiverName = $receiverName

$newRER.ReceiverClass = $receiverClassName

$newRER.ReceiverAssembly = $receiverAssemblyName

$newRER.ReceiverUrl = $receiverUrl

$newRER.Synchronization = $synchronization

$newRER.SequenceNumber = 100

 

try

{

$list.EventReceivers.Add($newRER)

$list.Update()

$context.ExecuteQuery()

Write-Host "Receiver added successfully"

}

catch

{

Write-Error "Failed to add receiver - error:  $_"

}

}

 

# define ER attributes

$receiverName = "OnDocumentAdding"

$receiverClassName = ""

$receiverEventType = [Microsoft.SharePoint.Client.EventReceiverType]::ItemAdding

$receiverSynchronization = [Microsoft.SharePoint.Client.EventReceiverSynchronization]::Synchronous

$receiverUrl = "https://rer-url/Services/DocumentEventReceiver.svc"

$receiverAssemblyName = ""

 

# now call function..

addListItemRemoteEventReceiver $clientContext $listTitle $receiverEventType $receiverSynchronization $receiverName $receiverUrl $receiverAssemblyName $receiverClassName