Add / Remove event receivers to list / content types in SharePoint with PowerShell

Although it’s simple but it’s a little bit tricky. Adding / removing an event receiver to a list and content type is the same you just need to use the appropriate collection is an SPWeb object.

Here is how to add / remove an event receiver to / from a list:

# The following code registers an event receiver for when an item is being added to a list
$web = Get-SPWeb "http://yourwebsiteurl"
$list = $web.Lists["your list name"]
$list.EventReceivers.Add("ItemAdding", "Full Assembly Name", "Full.Class.Name")

Removing an event receiver is as easy as:

# Be careful about the index value for when you have more than one event receiver!
$list.EventReceiver[0].Delete()

As you can see below adding an event receiver to a content type is very similar:

# The following code registers an event receiver for when an item is being added to a list
$web = Get-SPWeb "http://yourwebsiteurl"
$ctype = $web.ContentTypes["your content type name"]
$ctype.EventReceivers.Add("ItemAdding", "Full Assembly Name", "Full.Class.Name")

And so is deleting it:

# Be careful about the index value for when you have more than one event receiver!
$ctype.EventReceiver[0].Delete()

Now more important is the tricky part. If you have used this content type to create other / list instances then you should also call the following command to propagate the change:

$ctype.Update($true)
Advertisements
Add / Remove event receivers to list / content types in SharePoint with PowerShell

Check whether a website exists in a site collection

The easiest way I found is

// Checks whether a website exists by looking up its url in the current site collection
bool WebExistsByUrl(string url)
{
return SPContext.Current.Site.AllWebs.Any(w => w.Url.Equals(url, System.StringComparison.InvariantCultureIgnoreCase));
}

// Checks whether a website exists by looking up its name in the current site collection
public static bool WebsiteExistsByName(string name)
{
return Array.Exists(SPContext.Current.Site.AllWebs.Names, n => n == name);
}

or even better you can put them in an extension class to be more accessible:

public static class SiteExtensions
{
    // Checks whether a website exists by looking up its name
    public static bool WebExistsByName(this SPSite site, string name)
    {
        return Array.Exists(site.AllWebs.Names, n => n == name);
    }

    // Checks whether a website exists by looking up its URL
    public static bool WebExistsByUrl(this SPSite site, string url)
    {
        return site.AllWebs.Any(w => w.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase));
    }
}
Check whether a website exists in a site collection