Wednesday, 24 August 2011

Creating a retention policy to start a workflow in SharePoint 2010 using PowerShell

The script in this article was inspired by this one from Yaroslav Pentsarskyy, where he uses PowerShell to create a retention policy in SharePoint 2010. This works well for the built-in expiration actions (see, but I thought it was worth publishing a revised script for creating a retention policy to start a workflow as it requires a few extra properties in the policy XML.

The scenario for this script was that I wanted to create a retention policy on a specific content type associated with the Pages library on a number of sites. The workflow itself was associated directly to the Pages library and not to a site content type. The retention policy must start the workflow for each page, 20 days after it is created in the Pages library.

The workflow was created in SharePoint Designer and called “Review Page” - all it does is set a Status column to Expired. I then assigned the workflow to the “Content Page” content type on the Pages library of a site (see this article for details on how to do this in PowerShell) with the association name “Review Page Test”, as shown below:

Workflow to content type

We can now use PowerShell to create a retention policy to start this workflow for any page associated with the “Content Page” content type 20 days after it is created in the Pages library. Before the script can be run, you will need to load the following function in a PowerShell console with the SharePoint add-ins loaded:

function Update-IMPStartWorkflow($siteURL, $wfAssociationName, $listName, $contentType, $WfStartColumn)

    #Get web object
    $web = Get-SPWeb $siteURL
    write-host "Examining site:"$web.Title"at"$web.ServerRelativeUrl -ForegroundColor green
        #Do the following if a list exists with the name specified by the user - e.g., Pages
        if ($web.Lists[$ListName]) {

            write-host $web.Title"has a list called"$ListName -ForegroundColor green
            #Get the list
            $list = $web.Lists[$ListName]
            #Create list policy if one does not exist already
            #$policy = [Microsoft.Office.RecordsManagement.InformationPolicy.ListPolicySettings]($list)
            #if (!$policy.ListHasPolicy)
            #    $policy.UseListPolicy = $true
            #    $policy.Update()
            #Get the content type
            $ct = $list.ContentTypes[$contentType]
            #Get the Workflow template (parent association) ID from the association name
            $wfAssociationId = $ct.WorkflowAssociations.GetAssociationByName($wfAssociationName, 1033).ParentAssociationId.ToString()
            #Get the start column internal name and Id
            $fieldId = $list.Fields[$WfStartColumn].Id.ToString()
            $fieldName = $list.Fields[$WfStartColumn].InternalName
            #Create a new policy
            [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::CreatePolicy($ct, $null)
            $newPolicy = [Microsoft.Office.RecordsManagement.InformationPolicy.Policy]::GetPolicy($ct)    
            #Generate policy XML using the values required,
            #injecting column and workflow details from the variables assigned above
            $newPolicyFeatureXml = "<Schedules nextStageId=`"2`">"+
            "<Schedule type=`"Default`">"+
            "<data stageId=`"1`">"+
            "<formula id=`"Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration.Formula.BuiltIn`">"+
            "<action type=`"workflow`" id=`""+$wfAssociationId+"`" />"+
            #Add retention policy      
            $newPolicy.Items.Add("Microsoft.Office.RecordsManagement.PolicyFeatures.Expiration", $newPolicyFeatureXml)
            write-host "Added retention policy to start workflow"$wfAssociation.Name"on content type"$ct.Name"for list"$list.Title"in site"$web.Title
            #Report if the site does not have the list specified by the user
            write-host $web.Title"does not have a list called"$listName -ForegroundColor red
        write-host "There has been an error:"$_ -ForegroundColor red
        #Dispose of the Web object

Note that the important part of this script is where you generate the XML for the policy and assign it to the $newPolicyFeatureXml variable. This XML defines the properties required for setting the event, action and recurrence details.

If you need to set a recurrence on the policy, then you can add some extra properties to the "<data stageId=`"1`">"+ line. For example, to set a recurrence period of every 1 day, replace this line with the following XML:

"<data stageId=`"1`" recur=`"true`" offset=`"1`" unit=`"days`">"+

Once the function has been loaded, it can be called with the following command to create a retention policy for the “Content Page” content type, on the Pages library of the site http://portal, to start the workflow with the association name “Review Page Test”:

Update-IMPStartWorkflow -siteURL http://portal -wfAssociationName "Review Page Test" -listName "Pages" -contentType "Content Page" -WfStartColumn "Created"

The Information Management Policies administration page on the Pages library for the “Content Page” content type should now look as follows:

Retention Policy

Another thing to note is how the workflow association ID is injected into the XML. An early draft of my script used the following line to get the workflow association ID:

$wfAssociationId = $ct.WorkflowAssociations.GetAssociationByName($wfAssociationName, 1033).Id.ToString()

However, running the script produced an “Invalid retention stage defined” error message in the Information Management Policies administration page against the retention policy:


To resolve this I needed to use the Parent Association ID (the workflow template) rather than the Association ID (the workflow instance), as follows:

$wfAssociationId = $ct.WorkflowAssociations.GetAssociationByName($wfAssociationName, 1033).ParentAssociationId.ToString()

I have added this information to the article in case you run into the same error message either in PowerShell or C# code and are looking for a solution…


  1. Phil, I am trying to run your script, but I get the following error: There has been an error: You cannot call a method on a null-valued expression. Ideas? It finds the site and the library, but then throws the error.

  2. Hi,

    I have same issue for OOTB SPD workflow.
    I only have one action in SPD i.e send email , i also tried to set the description column some value. but it still says invalid retention stage defined.????

  3. The article you have shared here very good. This is really interesting information for me. Thanks for sharing!
    hotmail login |hotmail sign in |free hotmail login


  4. شركة فحص فلل بالرياض
    البيت السعيد
    شركة فحص فلل، أعمال الفحص للفلل الجديدة والقديمة من خلال مهندسين خبرة في مجال الفحص و الترميم من شركة البيت السعيد شركة فحص فلل بالرياض ، من خلال أدوات وأجهزة تكشف عن ما يحتاج إلى التعديل بمختلف أركان المكان، شركتنا متخصصة في الفحص لجميع المباني السكنية وغيرها، وتقوم بتحديد التكلفة النهائية للمبنى المراد اقتنائه بعد مباشرة عملية الفحص لذا شركة البيت السعيد شركة فحص فلل بالرياض ثقه لا تقارن
    فحص فلل بالرياض
    البيت السعيد
    للاستفسار عن جميع خدمات البيت السعيد عزل مائي و عزل حراري و عزل اسطح و عزل خزانات و عزل فوم وجميع انواع العوازل و رش مبيد و مكافحة حشرات و تسليك مجاري و شركة كشف تسربات المياه و فحص فللو صيانة مباني و ترميم منازل و نقل عفش و اثاث بالرياض يرجي الاتصال على 0543578920
    او زورو موقعنا على الانترنت

  5. You should come here to learn more and more.............
    EaseUS Partition Master 12.8 Key
    EaseUS Partition Master PRO 12.5 Crack & Serial Key Download is the disk that is comprehensive is the permanent unit and system optimization pc software for Windows-based administration without data loss or any risk.

    COREL DRAW X8 Keygen + Crack
    Corel Draw x8 Keygen is truly well known and worlds most excellent graphics software. Corel Draw x8 Keygen can create your pictures amazingly with greatest editing tools and latest supportive stuff.

  7. Avast Internet Security License Key
    Avast Internet Security has always been at the top of providing protection to your systems for a long time. Their latest version of security named as Avast Internet Security is a robust security suite that consists numerous tools to protect your system.


  8. نقل اثاث من الرياض الى الكويت 0507716412

    شركة شحن عفش من الرياض الى الكويت

    نقل اثاث من الرياض الى الاردن 0507716412
    شركة شحن عفش من الرياض الى الاردن

    شركة نقل اثاث من الرياض الى الدمام
    شركة نقل عفش من الرياض الى الدمام

    نقل اثاث من الرياض الى الامارات 0507716412

    شركة شحن عفش من الرياض الى الامارات

    نقل اثاث بالمدينة المنورة

    نقل عفش في المدينة المنورة

  9. This comment has been removed by the author.

  10. Thank you for your support who has read our article. I'm very happy if you can share our article below

    Toko Obat Herbal
    Cara Mengatasi Nyeri Sendi
    Obat Penyakit Jantung
    Cara menambah HB darah
    Cara Mengobati Milia

  11. Simply submission the best place a bet, You are investing buy specific commodity from the owner if you're the irresistible prospective buyer. You read and admit the world shipping charges application t's and c's starts in brand name new time frame or it may be bill. Scan premiums previous quotes unquestionably is short sale change within the event you acceleration you the greatest put money on sum..

    3. Der Verkufer kann Angebote i have to dfb trikot müller be Auktionsformat zustzlich amazon müller trikot durch einer Sofort Kaufen Funktion versehen. Diese kann von einem Kufer ausgebt werden, Solange noch kein Gebot auf family room Artikel abgegeben Coach Outlet Online Store oder ein Mindestpreis maillot de foot personnalise noch nicht erreicht wurde.

    This amazing sum of Maglie Poco Prezzo money comes along with topical practices works, Place a burden on, Broker and also other extra charges. The item money manuel neuer trikot rot is juegos de futbol susceptible to change before make expenses. The local surf maillot foot 2018 forecast in an western european subscriber Maglie Calcio Poco Prezzo express anyway us, Transfer cask on this subject select Maillot De Foot Pas Cher certainly not recoverable.

  12. When running any site, you need to do all that you can secure it. To begin securing your WordPress site, you should first make a reinforcement of your WordPress database and your fundamental website backup records (transfers, modules, subjects, and so forth.).

  13. Thank you very much because you have always shared many new things to us
    I am very happy because I can get articles that are very weighty contents
    Maybe I will come back to your site. Greetings :)

    Obat Encok Obat Sesak Nafas Obat Batu Kandung Kemih Obat Penghilang Jerawat Obat Gastritis Obat Sakit Lutut Cara Menghilangkan Jerawat Bruntusan Cara Menyembuhkan Kaki Pecah-Pecah Obat Batuk Rejan Cara Menghilangkan Nyeri Haid

  14. También puede visitar una tienda de ladrillo y mortero de Michael Kors o su sitio web y comprar directamente un bolso Michael Kors desde allí. Usar un bolso de Michael Kors les permite a los demás reconocer que el habitante urbano educado toma la moda realmente con seriedad. Los bolsos de hombro son particularmente refinados y elegantes.

    {Bolsas Michael Kors Precios | Bolsos Michael Kors Outlet | Michael Kors Rebajas}

    En vacker konstnärlig skapelse av vävt läder, som ger ett skalskaligt utseende - liknar en snakeskin eller fiskhud, linjer utsidan av påsen. Läderens bältros är små läderringar. Det finns också gyllene accenter på väskan. Slutresultatet är svagt liknar kedjepost.

    {Michael Kors Rea | Michael Kors Väska Rea | Michael Kors Plånbok}

  15. A beautiful purse or handbag from Coach Outlet Online can last for many years, and represent a great overall value.
    There are Michael Kors Bags Outlet in a large number of shopping malls located throughout the country.
    Cheap Michael Kors Bags is a great way to determine which models best suit your needs.
    Official Coach Factory Outlet Online all strive to provide comfort and convenience for their owners and the seams are double-stitched for maximum durability.
    Michael Kors Factory Store, has one of the most popular handbag and accessory lines on the market today.
    Coach Handbags Wholesale says a lady is classy, elegant and sophisticated.
    Coach Store Near Me trends come and go, but a Coach stands the test of time.
    The official Michael Kors Handbags On Sale Outlet regularly posts various handbags being offered for sale.
    Compare your Coach Bags On Sale Outlet to the logo provided on the website to make sure it is similar.
    All Michael Kors Outlet Online Store have serial numbers.


  16. Our client can choose any of them as per their convenient. We are also open to send our angels any other place of your choice. Escorts Service in Aerocityare waiting eagerly to meet you. You need to decide whether you want to meet them at home or at any hotel. If you are facing any challenges in arranging any place, let me inform you that we have tie-ups with 3 start hotels as well as 5 start hotels. Check our other services...
    Escorts Service in Aerocity
    Escorts Service in Aerocity
    Escorts Service in Aerocity
    Escorts Service in Aerocity
    Escorts Service in Aerocity

  17. Whenever there is a refreshing Coach Bags Clearance available the hype around the world is hard to picture. When you are paying a very high price tag for your Michael Kors Purses Sale you of course want it to be of a very high quality and that is what Coach Factory Outlet Online will supply you with. And you'll also find a best Ray Ban Outlet online.

    To find out if the logo in your New Yeezys is real or not, you can go online, and see correctly just what authentic Yeezy Boost 350 logo looks like. If the Cheap Air Force Onesthat you are planning to buy has a logo, which is even slightly different then it is surely not an original one. If you're getting Cheap Jordan Shoes For Men at reasonable price,just click here.


  19. Are you on the lookout of genuine Suzuki Parts? Are you tired of running around to check the availability of the required spare parts with the local dealers? Sit back and relax! BP Auto Spares India is here to cater to every need and requirement of auto parts! Contact them to order original Suzuki Spare Parts at great prices and enjoy immense savings of your time, efforts, and money!

  20. It's fantastic that you are getting ideas from this post as well as from our discussion made here.I have enjoyed reading your articles. It is well written. It looks like you spend a large amount of time and effort in writing the blog. I am appreciating your effort.Mobile App Development Company in Germany

  21. SystemRescueCd Crack (Latest Version 2022) Free Download: A blog that discusses the system rescue cd.