[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$PSshell = Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorVariable err -ErrorAction SilentlyContinue
if($PSshell -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$webUrl = '<<WebUrl>>'
#get web reference
$spWeb = Get-SPWeb $webUrl
#set event receiver properties
$list = $spWeb.Lists["<<ListName>>"]
$assembly = "<<FullyQualifiedAssemblyName>>" #Example: <<AssemblyName>>, Version=<<AssemblyVersion>>, Culture=neutral, PublicKeyToken=<<PublicKeyToken>>
$class = "<<ReceiverClassNameStartingWithNamespaceName>>" #Example: <<NamespaceName>>.<<ClassName>>
$eventType = "ItemAdded" # event type (ItemAdded / ItemUpdated)
#flag to check if the event receiver is already attached with the specified list
$flag=0
#get count of event receivers attached to specified list for checking if the specified event receiver is already attached with the specified list
$eventsCount = $list.EventReceivers.Count - 1
#if there is any event receiver attached to specified list
if($eventsCount -ge 0)
{
#iterated through the list of event receivers
for ($i = 0; $i -le $eventsCount; $i+=1)
{
#check if the specified event receiver is already attached with the specified list. If yes, set the flag and exit the loop.
if ($list.EventReceivers[$i].Assembly -eq $assembly -and
$list.EventReceivers[$i].Class -eq $class -and
$list.EventReceivers[$i].Type -eq $eventType)
{
Write-Host "Event receiver already attached."
$flag=1
break
}
}
}
#if specified event receiver is not attached with specified list then attach it
if($flag -eq 0)
{
Write-Host "Attaching event receiver."
$spEventReceiver = $list.EventReceivers.Add()
$spEventReceiver.Assembly = $assembly
$spEventReceiver.Class = $class
$spEventReceiver.Name = $eventType
$spEventReceiver.Type = 10001
$spEventReceiver.SequenceNumber = 10000
$spEventReceiver.Update()
Write-Host "Event receiver attached."
}Code snippet for attaching event receiver to SharePoint list using PowerShell script.
