Set-SCSMTemplateWithActivities powershell script

UPDATE 02-01-2014: Fixed some issues in script

 

When dealing with the cmdlet: Set-SCSMTemplate in SMLets, you might have noticed that if you apply a template with activities, the prefix of the ID’s (e.g. RA300 or MA250) is all missing. And it’s the same issue if done via the SDK or Orchestrator.

One workaround, described by Lee Berg here: http://www.leealanberg.com/blog/2013/03/13/scsm-automated-service-request-smlets-creation-issues-and-work-arrounds/ is to modify the management pack that contains the template, and then insert the prefix like this: MA{0}. This approach works, but can be quite cumbersome as it takes time to do and also “locks” the template so any modification done to the template via the console will reset the id property in the management pack. Which means you have to insert the property again in the management pack.

This script takes care of the problem with no need to modify the management pack. All you need to provide is the workitem guid and the guid or displayname of the template that you want to apply.

If you are using Orchestrator, then my collegue Jakob has made a cool Integration pack that takes care of the problem: http://blog.ctglobalservices.com/jgs/scoscsm-2012-create-objects-with-activities-with-coretech-integration-pack-for-scsm-2012-extension-beta-2/

My script is used when you want to apply a template on an already created workitem, where Jakob’s IP is used for creating new workitems based on a template. The same issue will happen in both scenarios. If people find the script useful I could make another script to create a new workitem based on a template as well.

This is the first version, I’d be happy to get your feedback:

Script:

The highlevel steps in the script is to

  1. Analyze the template for activities,
  2. Update the template with the right activity prefixes, and then finally
  3. Commit the updated template to the workitem.

Nothing is being changed or needs to be changed in the management pack with this method.

 

Usage:

Download:

http://gallery.technet.microsoft.com/Set-SCSMTemplateWithActivit-7343d96a

Leave a comment or write me an email for feedback

Cheers

Morten

By | 2013-12-27T15:05:28+00:00 December 27th, 2013|Powershell, Scripting & Development, Service Manager (SCSM)|18 Comments

About the Author:

Morten Meisler

Consultant / Developer / Trainer

Key areas / products:

  • System Center Service Manager
  • System Center Operations Manager
  • Automation (System Center Orchestrator / Service Management Automation (SMA))
  • Development: C#.Net, Powershell, SQL, Web development / HTML5 (Javascript,jQuery,CSS,HTML, Wordpress etc.)

18 Comments

  1. John Croson December 30, 2013 at 17:12 - Reply

    Thanks so much for this script! My struggle however, is that it complains that Class Name System.Reviewer is not supported. Why do you think this could be happening?

    PS C:Userssvc_scsmDesktop> $crObject.get_id()

    Guid
    —-
    9693aaea-96e9-0b2f-407b-6b9299ef40f7

    PS C:Userssvc_scsmDesktop> $template.get_id()

    Guid
    —-
    fc7b4076-77cf-ea88-6204-13dd064ec2ee

    PS C:Userssvc_scsmDesktop> C:exportSCSMSet-SCSMTemplatewithActivities.ps1 -Id $crObject.get_id() -TemplateId $template.get_id()
    Class Name System.Reviewer is not supported
    At C:exportSCSMSet-SCSMTemplatewithActivities.ps1:41 char:19
    + else {throw “Class Name $ClassName is not supported”}
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : OperationStopped: (Class Name Syst…s not supported:String) [], RuntimeException
    + FullyQualifiedErrorId : Class Name System.Reviewer is not supported

    Thank you!!

    • Morten December 30, 2013 at 17:40 - Reply

      Looks like a bug in script where system.reviewer is included in the regex, ill look into it soon when I get to a PC 🙂

    • Morten January 2, 2014 at 11:13 - Reply

      Ok, the issue has been fixed now so it only looks at objects of Activity and runbook class type.

    • Tuesday December 23, 2016 at 5:29 - Reply

      Hallo, ich würde gerne VILLAGE spielen, das Keeinrspnel des Jahres 2012. Falls jemand Lust hat, bitte einfach melden. Ich würde das Spiel mitbringen, habe die Regeln aber noch nicht studiert.

    • http://www./ December 30, 2016 at 7:43 - Reply

      If your articles are always this helpful, “I’ll be back.”

    • bmw or mercedes February 18, 2017 at 22:08 - Reply

      Usually I do not read post on blogs, but I would like to say that this write-up very forced me to check out and do so! Your writing style has been surprised me. Thanks, very great article.

  2. […] Coretech Morten Meisler – Set-SCSMTemplateWithActivities powershell script http://blog.coretech.dk/mme/set-scsmtemplatewithactivities-powershell-script/ […]

  3. […] –      Coretech Morten Meisler – Set-SCSMTemplateWithActivities powershell script http://blog.coretech.dk/mme/set-scsmtemplatewithactivities-powershell-script/ […]

  4. Frank February 7, 2014 at 12:10 - Reply

    All My Activities are in state pending. Activities are not started.
    Only if I afterwards set the first activity to in progress.
    Do you have the same behaviour ?

  5. Morten February 7, 2014 at 12:24 - Reply

    Hi Frank,
    This was an old issue that should have been fixed, it works fine in mine. What version are you using? Luckily the fix is easy enough, just set the first activity in the template to In Progress.
    I will see that it gets implemented in the script as soon as I got time.

  6. Jeremy Castleberry July 30, 2014 at 17:19 - Reply

    Morten! Thank you very much.

    With a little bit of finessing I was able to add bits of this to my script and fix the missing “RB/RA/MA”! Now when I spawn my new Service requests from PowerShell – they look “normal”.

    thank you again!

    Jeremy

    • Morten July 30, 2014 at 22:11 - Reply

      Hi Jeremy,

      That’s good to hear 🙂

      Feel free to send me updates to the code if you think it can be improved in any way.

  7. Patrick January 27, 2015 at 23:40 - Reply

    Hey, I’ve come up with a solution that quickly checks a whole management pack for missing prefixes and fixes them. Here’s the source:

    Repair-ManagementPackExport managementpackName.xml

    .INPUTS
    System.String

    .NOTES
    If this file does not have strings requiring repair, then it will not be modified.

    .VERSION
    1.1

    #>
    function Repair-ManagementPackExport
    {
    param ( [parameter(mandatory=$true)] [System.String] $xmlFileFullPath )

    # Select all nodes which contain a child path attribute that has a description, but does not contain a child path having an ID
    # note, special use of @ char, the last line with the “@ character must have no white space before it or the multiline string won’t be recognized
    [string] $xPathExpression = @”
    //*[
    Property[contains(@Path, “$Context/Property[Type=’CustomSystem_WorkItem_Library!System.WorkItem’]/Description$”)] and
    not (Property[contains(@Path, “$Context/Property[Type=’CustomSystem_WorkItem_Library!System.WorkItem’]/Id$”)])
    ]
    “@

    $ErrorActionPreference = “Stop”

    try
    {

    if (-not (Test-Path $XmlFileFullPath))
    {
    $msg = “The file $XmlFileFullPath does not exist.”
    throw [System.IO.FileNotFoundException] $msg
    }

    $xmlFileFullPath = Resolve-Path -Path $xmlFileFullPath

    [Xml.XmlDocument] $xdoc = Get-Content $XmlFileFullPath
    [Xml.XmlNodeList] $nodes = $xdoc.SelectNodes($xPathExpression)

    if ($nodes -eq $null)
    {
    Write-Host “No errors detected”
    return
    }

    [int] $nodeCount = $nodes.Count
    Write-Host “Starting Operation – Adding $nodeCount missing ID tags in XML”

    [Xml.XmlElement] $newNode = $null

    for ([int]$i=0; $i -lt $nodeCount; ++$i)
    {

    $newNode = $xdoc.CreateElement(‘Property’)
    $newNode.SetAttribute(‘Path’, ‘$Context/Property[Type=”CustomSystem_WorkItem_Library!System.WorkItem”]/Id$’)

    $newNode.InnerText = ”
    [Xml.XmlElement] $elementToInsertAfter = $null

    # check first to see if the activity type is defined at the higher level object. If it is, use this path since the children propty objects will only
    # contain generic system activity paths
    if ($nodes[$i].Path -ne $null)
    {
    $newNode.InnerText = ReturnIDType $nodes[$i].Path
    }

    foreach ($propElement in $nodes[$i].Property)
    {
    # only process if we haven’t found the element to insert after
    if ($elementToInsertAfter -eq $null)
    {
    # find the correct location to insert the new node (insert right below the ID node
    # this is being done because there are times when the objects that require this node insertion have nested objects. If the ID tag for the higher level object gets
    # inserted below the child object, it’ll be considered invalid, so just safer to place around title

    if ($propElement.Path.Contains(“`$Context/Property[Type=’CustomSystem_WorkItem_Library!System.WorkItem’]/Description$”))
    {
    $elementToInsertAfter = $propElement
    }
    }

    # only process if we haven’t yet found the activity type
    if ($newNode.InnerText -eq ”)
    {
    $newNode.InnerText = ReturnIDType $propElement.Path
    }

    # we found all the info we need, break out early
    if ( ($newNode.InnerText -ne ”) -and ($elementToInsertAfter -ne $null) )
    {
    break
    }
    }

    # the innerText is empty if we have a template without activities, in this case we do not need the ID
    if ($newNode.InnerText -ne ”)
    {

    if ($elementToInsertAfter -eq $null)
    {
    throw “We have an issue with the XML formation. Expected Description tag is missing. Please review the Management pack file being submitted.”
    }

    $tmp = $nodes[$i].InsertAfter($newNode, $elementToInsertAfter);
    }
    }

    # we don’t have a document encoding element, add one so that we don’t lose character encoding
    if ($xdoc.DocumentElement.OwnerDocument.xml -eq $null)
    {
    [Xml.XmlElement] $root = $xdoc.DocumentElement
    [Xml.XmlDeclaration] $xmldecl = $xdoc.CreateXmlDeclaration(“1.0″,”UTF-16″,””)
    $tmp = $xdoc.InsertBefore($xmldecl, $root)
    }

    $xdoc.Save($XmlFileFullPath)
    Write-Host “Completed Operation – Added $nodeCount missing ID tags in XML.”
    }
    catch
    {
    # Throwing an exception in this manner will actually bubble up to the Orchestrator runbook activity and give an error condition.
    Throw
    }
    }
    Export-ModuleMember -Function Repair-ManagementPackExport

    #region Private functions

    function ReturnIDType
    {
    param ( [parameter(mandatory=$true)] [System.String] $pathText )

    # only load this settings object once (create a script level variable, acting like a static for this session)
    if ($script:activitySettingsObj -eq $null)
    {
    $script:activitySettingsObj = Get-SCSMObject -Class (Get-SCSMClass -Id “5e04a50d-01d1-6fce-7946-15580aa8681d”)
    }

    [string] $retVal = ”

    if ($pathText.Contains(“Microsoft.SystemCenter.Orchestrator.RunbookAutomationActivity”))
    {
    $retVal = $script:activitySettingsObj.MicrosoftSystemCenterOrchestratorRunbookAutomationActivityBaseIdPrefix
    }
    elseif ($pathText.Contains(“System.WorkItem.Activity.ManualActivity”))
    {
    $retVal = $script:activitySettingsObj.SystemWorkItemActivityManualActivityIdPrefix
    }
    elseif ($pathText.Contains(“System.WorkItem.Activity.ReviewActivity”))
    {
    $retVal = $script:activitySettingsObj.SystemWorkItemActivityReviewActivityIdPrefix
    }
    elseif ($pathText.Contains(“System.WorkItem.Activity.ParallelActivity”))
    {
    $retVal = $script:activitySettingsObj.SystemWorkItemActivityParallelActivityIdPrefix
    }
    elseif ($pathText.Contains(“System.WorkItem.Activity.SequentialActivity”))
    {
    $retVal = $script:activitySettingsObj.SystemWorkItemActivitySequentialActivityIdPrefix
    }
    elseif ($pathText.Contains(“System.WorkItem.Activity.DependentActivity”))
    {
    $retVal = $script:activitySettingsObj.SystemWorkItemActivityDependentActivityIdPrefix
    }

    if ($retval -ne ”) { $retVal += “{0}” }
    return $retVal
    }

    #endregion

  8. Ed Shepherd December 2, 2015 at 16:47 - Reply

    You sweet Beautiful Ginger Man!

    This is simply brilliant! I don’t know how I didn’t find this post last year when we first had the issue, but its really going to save our sanity, as we implement change and release as we are automating the creation of as much of this as we can!

    from your Ginger UK Brother!

    Ed

  9. Chunfeng Zhang March 15, 2016 at 4:32 - Reply

    Thank you very much for the author to solve my problem.I met the question is, can’t find the first activity in the template and its status is set to start.On the basis of the author code changes:
    Note: in the template avtivities number order must, from top to bottom is growing up.
    1:Changes in the Apply-SCSMTemplate function.

    #Update Activities in template
    [int]$count = 0
    foreach ($TemplateObject in $Template.ObjectCollection)
    {
    Update-SCSMPropertyCollection -Object $TemplateObject
    $count++;
    }

    2:Changes in the Update-SCSMPropertyCollection function.

    #Regex – Find class from template object property between ! and ‘]
    $pattern = ‘(?<=!)[^!]+?(?=''])'
    if (($Object.Path) -match $pattern -and ($Matches[0].StartsWith("System.WorkItem.Activity") -or $Matches[0].StartsWith("Microsoft.SystemCenter.Orchestrator")))
    {
    #Handle the first Activity
    if ($count -eq 0)
    {
    #Create template property object
    $propClass = [Microsoft.EnterpriseManagement.Configuration.ManagementPackObjectTemplateProperty]
    $propObject = New-Object $propClass

    #Add new item to property object
    $propObject.Path = "`$Context/Property[Type='$aliasActivity!System.WorkItem.Activity']/Status$"
    $propObject.MixedValue = "11fc3cef-15e5-bca4-dee0-9c1155ec8d83"

    #Add property to template
    $Object.PropertyCollection.Add($propObject)
    }

    #Set prefix from activity class
    $prefix = Get-SCSMObjectPrefix -ClassName $Matches[0]


    }

  10. run dragon city online generator September 12, 2017 at 2:02 - Reply

    … [Trackback]

    […] Find More here|Find More|Read More Informations here|There you can find 90150 additional Informations|Infos on that Topic: blog.ctglobalservices.com/service-manager-scsm/mme/set-scsmtemplatewithactivities-powershell-script/ […]

  11. Porky November 11, 2017 at 8:02 - Reply

    This script deservingly merits full praise, well done in figuring out the required objects and how to apply them to automate a request offering. For someone that has just stepped aboard the SCSM platform a fortnight ago, I did not know where to start. This script has saved my skin. Thank you,

Leave A Comment