Update list items to trigger event handler through PowerShell

Published on Monday, February 25, 2013

Scenario: A SharePoint list has different content types associated with it and every content type has a field of type taxonomy (connected to managed metadata termstore). And that list has an event handler attached to it that is triggered on item add and item update. In that event handler, you push the change to user profile property (for respective user profile) that is also of type managed metadata. So basically when you add or update an item in the list, that value is written back in a user profile property.

Now, under normal circumstances everything should work fine as event handler will kick in and write back the values to user property. However, if you have to delete the user profile or due to different reasons, the values in user profile is wiped off etc, you need to ensure that the data already inserted in the list is also present in the user profile.


For such scenarios, what we need to do is trigger the event handler on every list item so that the value is written back to user profile property. PowerShell comes to our rescue in such situation!

Here is the powerShell script for that

Function UpdateListItems($webAppUrl)
     #Get Site Collections for respective web applications
     $sitecolls = Get-SPSite -WebApplication $webAppUrl

     Write-Host "Total number of site collections: " $sitecolls.Count

     #Iterate through every site collection to find the list at the root web
     foreach($siteCol in $sitecolls)
        $site = Get-SPSite $siteCol.Url

        Write-Host "Site Collection: " $site.Url
        $rootSite = $site.RootWeb

        Write-Host $rootSite.Name

        #Retrieve the list
        $list = $rootSite.Lists["ListName"]

        if($list -ne $null)

         # Fetch list items only for required content type (If this needs to execute for every content type,
         # just remove the filter from following statement, just write $listItems = $list.Items)
         $listItems = $list.Items | ?{$_.ContentType.Name -eq "ContentTypeName"}

         foreach($item in $listItems)
           Write-Host $item["Field's Dislay Name"]

           #Update the item

Now once the function is defined, call it for execution.

UpdateListItems "http://mysite.mydomain.com"

One thing to notice in the script above is that we are using RunWithElevatedPrivileges. My Colleague Matthias Einig has written an amazing post on his blog regarding this, do check it out.

Hope it helps.

comments powered by Disqus