Using PowerShell With SharePoint – an example
Posted by fredmorrison on 2008-06-04
I recently needed to clean out some tasks from the task lists on my development box. Unfortunately, I had attached an ItemDeleting event receiver to most of the task lists as part of a custom workflow. The event receiver prevents a task assignee from deleting their assigned task. Instead of writing a C# console application, I wrote the PowerShell utility (using my favorite tool, PowerGUI) shown below and simply typed the following at a PowerShell prompt to remove all the ItemDeleting event receivers from all the lists:
SPRemoveItemDeletingEventReceivers http://workflow2/FredsWfTestSite
# SPRemoveItemDeletingEventReceivers.ps1
#
# Purpose: Removes any ItemDeleting Event Receivers from all lists on the specified site collection
#
# Example: SPRemoveItemDeletingEventReceivers http://workflow2/FredsWfTestSite
#
# show what we expect in the form of parameters to be passed to this script
param([string] $siteName)
# following makes it easier to work with SharePoint and also means you have to run this script on the SharePoint server
[void] [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint' ) | Out-Null
$site = New-Object -TypeName Microsoft.SharePoint.SPSite $siteName
[Microsoft.SharePoint.SPWeb] $web = $site.OpenWeb()
[Microsoft.SharePoint.SPListCollection] $lists = $web.Lists
Write-Host $sites.Count
[Microsoft.SharePoint.SPList] $list = $null
[int] $iList = 0
for( $iList=0; $iList -lt $lists.Count; $iList++)
{
$list = $lists[$iList]
# since we only attached an ItemDeleting event receiver to task lists, only look at the those types
if ( $list.BaseTemplate -eq 'Tasks' )
{
[string] $listTitle = $list.Title
Write-Host $list.Title $list.EventReceivers.Count
[int] $evIdx = 0
[bool] $found = $false
# for every Event Receiver defined for the list ...
for($evIdx = 0; $evIdx -lt $list.EventReceivers.Count; $evIdx++)
{
# get a reference to the Event Receiver
[Microsoft.SharePoint.SPEventReceiverDefinition] $er = $list.EventReceivers[$evIdx]
# if it's a type we care about ...
if ( $er.Type -eq 'ItemDeleting' )
{
[string] $erType = $list.EventReceivers[$evIdx].Type
# get rid of it
$list.EventReceivers[$evIdx].Delete()
Write-Host "Removed an $erType Event Receiver from $listTitle"
$found = $true
}
# if we removed any of the specified Event Receivers from the list, update the list
if ($found)
{
$list.Update()
}
}
}
}
Write-Host 'Done'