Web Event Receivers: Attach using PowerShell

The following is a simple PowerShell script for attaching SharePoint web event receivers. It is clever enough to check if they have already been attached and hence to avoid duplication.

There are no “gotchas” or anything really worth noting here. This example is pretty much the same as the dozens of list item event receiver examples out there, just targeting a different event receiver type. I am only posting it because I was so surprised that I had to write it myself after failing to find an example to ‘steal’ from the internet – maybe I wasn’t looking hard enough.

The first half of the script is the bit you’ll be interested in (if you are interested in any of it!), the second half is just a usage example.

# Defintion of function to attach web event receivers
# if they are not already added
Function AddWebEventReceivers($webER) 
  $assembly = "*fully_qualified_assembly_name*"
  $class = "*class_name_including_namespace*"

  # Only attach receivers if there aren't already added
  # You can make the check more specific by checking the Type
  # property as well if required
  $existingER = $webER.EventReceivers | Where { $_.Class -eq $class }
  if($existingER -eq $null -or $existingER.length -eq 0)
    $webER.EventReceivers.Add("WebMoved", $assembly, $class)

# Iterate all webs and attach the web event receivers to
# sites based on a certain web template
$site = Get-SPSite "*webAppUrl*"
$allWebs = $site.AllWebs
foreach($web in $allWebs)
    # Only act on certain sites
    if($web.WebTemplateId -eq 100009 -and $web.Configuration -eq 2)
  catch [System.Exception]
    $errorMessage = $Error[0]
    Write-Host "Failed: $errorMessage" -NoNewline -F Red

Published by

Paul Ryan

As a developer my professional interests are technical and tend to be SharePoint focused. I've been working with SharePoint since 2009 and hope my posts will give back a little to the community that's supported me over this time. I'm also a keen runner (half-marathon) and passionate Brompton bicycle owner.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.