Adding Event Receivers with PowerShell

Here’s my little script for removing and adding Event Receivers with PowerShell.

You’ll need to update the first four lines that set the web, list, assembly and class names and then adjust the events you want to register at the end of the script. I hope you find this useful….

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

## setup our properties
$SiteUrl = "
http://your.web.url/goes/here"
$ListName = "Elements"
$assembly = "your.assembly.name, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d09fbe311db6826"
$class = "your.assembly.name.classname"

## function to add the receiver
Function AddReceiver($type)
{  
    Write-Host "    Adding receiver: $type – $assembly – $class" -nonewline
    try {
        $OpenList.EventReceivers.Add("ItemAdded", $assembly, $class)
        Write-Host " – done" -foreground green  
    }
    catch {
        Write-Host " – error adding receiver : $_" -foreground red  
    }
}


## open the web site
Write-Host "Opening web ‘$SiteUrl’" -nonewline
$OpenWeb = Get-SPWeb $SiteUrl -EA Stop
Write-host " – done " -foreground green

## open the list
Write-Host "Opening ‘$ListName’ list" -nonewline
$OpenList = $OpenWeb.Lists[$ListName]
if ($OpenList -eq $null)
{
    Write-host " – can’t open list " -foreground red
    return
}
else
{
    Write-host " – done " -foreground green
}

## remove any existing event receivers
Write-Output "Removing existing event receivers:"
$count = $OpenList.EventReceivers.Count
if ($count -gt 0)
{
    for( $x = $count -1; $x -gt -1; $x–)
    {
        $Receiver = $OpenList.EventReceivers[$x] ; $t = $Receiver.Type ; $a = $Receiver.Assembly ; $c = $Receiver.Class
        Write-Host "    [$x] – $t – $a – $c" -nonewline
        $Receiver.Delete()
        Write-Host " – done " -foreground green
    }
}
else
{
    Write-Host "    – no existing EventReceivers found." -foreground green
}

## add new event receivers
Write-Host "Adding new event receivers:"
## add a new row for each type required to be registered
AddReceiver("ItemAdded")
AddReceiver("ItemUpdated")

Write-Host "-FIN-" -foreground green

I hope you find this useful…

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: