lib/Recipes.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715


# Recipes
Function Get-TMRecipe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false)]
        [String]$Name,

        [Parameter(Mandatory = $false)]
        [Switch]$ResetIDs,

        [Parameter(Mandatory = $false)]
        [String]$SaveCodePath,

        [Parameter(Mandatory = $false)]
        [Switch]$AsJson,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru

    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }
    process {

        # Format the uri
        $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/list?archived=n&context=All"
        try {
            $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
        } catch {
            return $_
        }

        if ($response.StatusCode -in @(200, 204)) {
            $Result = ($response.Content | ConvertFrom-Json).data.list
        } else {
            return 'Unable to collect Recipes.'
        }

        ## Get each recipe's Source Code in the list
        for ($i = 0; $i -lt $Result.Count; $i++) {

            ## Get the Recipe in standard format
            $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/$($Result[$i].recipeId)"
            try {
                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
            } catch {
                return $_
            }
            if ($response.StatusCode -in @(200, 204)) {
                $Result[$i] = ($response.Content | ConvertFrom-Json).data
            } else {
                return 'Unable to collect Recipe.'
            }

            ## Get the Recipe in JSON Format
            $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/$($Result[$i].recipeId)?format=json"
            try {
                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
            } catch {
                return $_
            }

            if ($response.StatusCode -in @(200, 204)) {
                $RecipeData = ($response.Content | ConvertFrom-Json).data
                Add-Member -InputObject $Result[$i] -NotePropertyName 'sourceCodeJson' -NotePropertyValue $RecipeData.sourceCode
            } else {
                return 'Unable to collect Recipe.'
            }
        }

        if ($ResetIDs) {
            for ($i = 0; $i -lt $Result.Count; $i++) {

                ## Null the Recipe ID and Event
                $Result[$i].recipeId = $null
                if ($Result[$i].context.eventId) { $Result[$i].context.eventId = $null }
            }
        }

        ## Return the details
        if ($Name) {
            $Result = $Result | Where-Object { $_.name -eq $Name }
        } else {
            $Result = $Result
        }

        ## Save the Code Files to a folder
        if ($SaveCodePath) {

            ## Get a FieldToLabel map to build string replacements
            $LabelReplacements = [System.Collections.ArrayList]@()
            $FieldToLabelMap = Get-TMFieldToLabelMap

            ## Create a replacement token for each asset/label = field set
            foreach ($DomainClass in @('DEVICE', 'APPLICATION', 'DATABASE', 'STORAGE' )) {

                foreach ($FieldName in $FieldToLabelMap.$DomainClass.Keys) {
                    if ($FieldName -match 'custom\d+') {

                        # Write-Host $FieldName
                        [void]($LabelReplacements.Add([pscustomobject]@{
                                    DomainClass = $DomainClass
                                    FieldLabel  = $FieldToLabelMap.$DomainClass.$FieldName
                                    FieldName   = $FieldName
                                }
                            )
                        )
                    }
                }
            }

            ## Save Each of the Script Source Data
            foreach ($Item in $Result) {

                ## When using ResetIDs, custom field numbers will be converted to a "custom5|DEVICE|DSID-vCenter" Format
                if ($ResetIDs) {

                    ## Replace all 'customN' items with a codestring to replace the correct items in the offline package
                    $SourceCodeLines = $Item.sourceCode -split "`r`n" -split "`r" -split "`n"
                    $UpdatedSourceCodeLines = [System.Collections.ArrayList]::new()
                    foreach ($SourceCodeLine in $SourceCodeLines) {
                        $CurrentLine = $SourceCodeLine
                        $LabelReplacements | ForEach-Object {
                            if ($CurrentLine -match $_.FieldName) {
                                $CurrentLine = $CurrentLine -replace $_.FieldName, "customN|$($_.DomainClass)|$($_.FieldLabel)|"
                            }
                        }
                        [void]($UpdatedSourceCodeLines.Add($CurrentLine))
                    }
                    $Item.sourceCode = $UpdatedSourceCodeLines -join "`r`n"


                    ## Replace all customN in the JSON Data
                    $SourceCodeLines = ($Item.sourceCodeJson | ConvertTo-Json -Depth 10) -split "`r`n"
                    $UpdatedSourceCodeLines = [System.Collections.ArrayList]::new()
                    foreach ($SourceCodeLine in $SourceCodeLines) {
                        $CurrentLine = $SourceCodeLine
                        $LabelReplacements | ForEach-Object {
                            if ($CurrentLine -match $_.FieldName) {
                                $CurrentLine = $CurrentLine -replace $_.FieldName, "customN|$($_.DomainClass)|$($_.FieldLabel)|"
                            }
                        }
                        [void]($UpdatedSourceCodeLines.Add($CurrentLine))
                    }
                    $Item.sourceCodeJson = $UpdatedSourceCodeLines | ConvertFrom-Json
                }

                ## Get a FileName safe version of the Provider Name
                $SafeScriptName = $Item.name -replace '\:', '-' -replace '\/', '-' -replace '\|', '-' -replace '\\', '-'

                ## Create the Provider Action Folder path
                Test-FolderPath -FolderPath $SaveCodePath

                ##
                ## Save the Recipe (JSON)
                ##
                $RecipeConfigFileName = Join-Path $SaveCodePath "$SafeScriptName.json"
                $RecipeCodeFileName = Join-Path $SaveCodePath "$SafeScriptName.groovy"

                ## Save the Source Code
                $Item.sourceCode | Set-Content -Path $RecipeCodeFileName -Force
                $Item.PSObject.Properties.remove('sourceCode')
                $Item | ConvertTo-Json -Depth 10 | Set-Content -Path $RecipeConfigFileName -Force
            }
        }

        if ($Passthru -or !$SaveCodePath) {
            return $Result
        }
    }
}


Function New-TMRecipe {
    param(
        [Parameter(Mandatory = $false)][String]$TMSession = 'Default',
        [Parameter(Mandatory = $true)][PSObject]$Recipe,
        [Parameter(Mandatory = $false)][Switch]$Update,
        [Parameter(Mandatory = $false)][Switch]$PassThru
    )
    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {

        ## Check for existing credential, or Create a shell
        $RecipeCheck = Get-TMRecipe -Name $Recipe.Name -TMSession $TMSession
        if ($RecipeCheck) {

            ## If Update is enabled, set the RecipeID for the update
            if ($Update) {
                $NewRecipeID = $RecipeCheck.recipeId
            } else {

                ## If Passthru is enabled, return the object
                if ($PassThru) {
                    return $RecipeCheck
                } else {
                    return
                }
            }
        } else {

            ## The Recipe needs to be created. Start by posting the name to get an ID
            $uri = 'https://'
            $uri += $TMSessionConfig.TMServer
            $uri += '/tdstm/ws/cookbook/recipe'

            ## Create a new Recipe
            $CreateNewRecipe = @{
                name        = $Recipe.name
                description = $Recipe.description
            } #| ConvertTo-Json

            ## Send the New recipe to the server
            Set-TMHeaderContentType -ContentType 'Form' -TMSession $TMSession
            $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $CreateNewRecipe
            if ($response.StatusCode -eq 200) {

                ## Convert the response content
                $responseContent = $response.Content | ConvertFrom-Json

                ## If Successful
                if ($responseContent.status -eq 'success') {

                    ## Created a new recipe ID, update the Recipe Object and save it.
                    $NewRecipeID = $responseContent.data.recipeId

                } else {
                    throw "Unable to add Recipe. $($ResponseContent.errors))"
                }
            } else {
                throw 'Unable to add Recipe.'
            }
        }

        ##
        ## Update or Create the Recipe
        ##

        $RecipeSourceCode = $Recipe.sourceCode

        $NewRecipe = Get-TMRecipe -Name $Recipe.name -TMSession $TMSession
        if ($NewRecipe) {
            $Recipe = $NewRecipe
        }

        ## With the Existing or New RecipeID Update the Recipe Data
        $UpdatedRecipe = @{
            recipeId              = $NewRecipeID
            name                  = $Recipe.name
            description           = $Recipe.description
            createdBy             = $Recipe.createdBy
            lastUpdated           = $Recipe.lastUpdated
            versionNumber         = $Recipe.versionNumber
            releasedVersionNumber = $Recipe.releasedVersionNumber
            recipeVersionId       = $NewRecipe.recipeVersionId
            hasWIP                = $Recipe.hasWIP
            sourceCode            = $RecipeSourceCode
            changelog             = $Recipe.changelog
            clonedFrom            = $Recipe.clonedFrom
        }

        # Update the newly created recipe with the data
        $uri = 'https://'
        $uri += $TMSessionConfig.TMServer
        $uri += '/tdstm/ws/cookbook/recipe/' + $NewRecipeID

        ## Send the Recipe (New or Update)
        Set-TMHeaderContentType -ContentType 'Form' -TMSession $TMSession
        $response = Invoke-WebRequest -Method Post -Uri $uri -WebSession $TMSessionConfig.TMWebSession -Body $UpdatedRecipe
        if ($response.StatusCode -eq 200) {

            ## Convert the response content
            $responseContent = $response.Content | ConvertFrom-Json

            ## If Successful
            if ($responseContent.status -ne 'success') {
                throw "Unable to add Recipe: $($responseContent.errors)"
            }
        }

        ## If Passthru is enabled, return the Updated Recipe
        if ($PassThru) {
            return (Get-TMRecipe -Name $Recipe.name -TMSession $TMSession)
        }
    }
}


Function Read-TMRecipeScriptFile {
    param(
        [Parameter(Mandatory = $true)]$Path,
        [Switch][Parameter()]$UpdateFieldNames
    )

    ## Handle JSON files
    $File = Get-Item -Path $Path
    if ($File.Extension -eq '.json') {

        ## Read the Json file
        $TMRecipe = Get-Content -Path $Path | ConvertFrom-Json

        if ($UpdateFieldNames) {

            ## Convert any Custom Field Label Tokens from a template
            ## Get a FieldToLabel map to build string replacements
            $LabelReplacements = [System.Collections.ArrayList]@()
            $FieldToLabelMap = Get-TMFieldToLabelMap

            ## Create a replacement token for each asset/label = field set
            foreach ($DomainClass in @('DEVICE', 'APPLICATION', 'DATABASE', 'STORAGE' )) {

                foreach ($FieldName in $FieldToLabelMap.$DomainClass.Keys) {
                    if ($FieldName -match 'custom\d') {

                        # Write-Host $FieldName
                        [void]($LabelReplacements.Add([pscustomobject]@{
                                    DomainClass = $DomainClass
                                    FieldLabel  = $FieldToLabelMap.$DomainClass.$FieldName
                                    FieldName   = $FieldName
                                }
                            )
                        )
                    }
                }
            }
        }

        ## This might be a JSON+Groovy pair
        $RecipeGroovyPath = $Path -Replace '.json', '.groovy'
        if (Test-Path $RecipeGroovyPath) {

            ## Replace all 'customN' items with a codestring to replace the correct items in the offline package
            $SourceCodeLines = (Get-Content -Path $RecipeGroovyPath -Raw) -split "`r`n" -split "`r" -split "`n"
            $UpdatedSourceCodeLines = [System.Collections.ArrayList]::new()

            if (-Not $UpdateFieldNames) {
                $UpdatedSourceCodeLines = $SourceCodeLines
            } else {
                foreach ($SourceCodeLine in $SourceCodeLines) {
                    $CurrentLine = $SourceCodeLine
                    $LabelReplacements | ForEach-Object {
                        $ReplaceString = "customN\|$($_.DomainClass)\|$($_.FieldLabel)\|"
                        if ($CurrentLine -match $ReplaceString) {
                            $CurrentLine = $CurrentLine -replace $ReplaceString, $_.FieldName
                        }
                    }
                    [void]($UpdatedSourceCodeLines.Add($CurrentLine))
                }
            }

            Add-Member -InputObject $TMRecipe -NotePropertyName sourceCode -NotePropertyValue $($UpdatedSourceCodeLines -join "`r`n") -Force

        }

        ## Remove JSON metadata that is only stored offline
        if ($TMRecipe.PSObject.Properties.Name -contains 'sourceCodeJson') {
            $TMRecipe.PSObject.Properties.Remove('sourceCodeJson')
        }

        return $TMRecipe
    }

}

# Function Publish-TMRecipe {
# [CmdletBinding()]
# param(
# [Parameter(Mandatory = $false)]
# [String]$TMSession = 'Default',

# [Parameter(Mandatory = $false)]
# [String]$Name,

# [Parameter(Mandatory = $false)]
# [String]$Server = $global:TMSessions[$TMSession].TMServer,

# [Parameter(Mandatory = $false)]
# [Bool]$AllowInsecureSSL = $global:TMSessions[$TMSession].AllowInsecureSSL
# )

# ## Get Session Configuration
# $TMSessionConfig = $global:TMSessions[$TMSession]
# if (-not $TMSessionConfig) {
# Write-Host 'TMSession: [' -NoNewline
# Write-Host $TMSession -ForegroundColor Cyan
# Write-Host '] was not Found. Please use the New-TMSession command.'
# Throw 'TM Session Not Found. Use New-TMSession command before using features.'
# }

# #Honor SSL Settings
# $TMCertSettings = $TMSessionConfig.AllowInsecureSSL ? @{SkipCertificateCheck = $true } : @{SkipCertificateCheck = $false }

# ## Get the Existing Recipe to publish
# $ServerRecipe = Get-TMRecipe -Name $Name -TMSession $TMSession
# if (-Not $ServerRecipe) {
# throw 'Recipe not found'
# }

# if ($ServerRecipe.hasWIP -eq $False) {
# Write-Host 'This recipe does not have a Work In Progress, and is already released.'
# return
# }

# # Format the uri
# $instance = $Server.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
# $uri = "https://$($TMSessionConfig.TMServer)/tdstm/ws/cookbook/recipe/release/" + $ServerRecipe.recipeId

# ## Set the Request to a Form post
# Set-TMHeaderContentType -ContentType 'FORM'
# $FormPostData = @{
# recipeId = $ServerRecipe.recipeId
# name = $ServerRecipe.name
# description = $ServerRecipe.description
# createdBy = $ServerRecipe.createdBy
# lastUpdated = $ServerRecipe.lastUpdated
# versionNumber = $ServerRecipe.versionNumber
# releasedVersionNumber = $ServerRecipe.releasedVersionNumber
# recipeVersionId = $ServerRecipe.recipeVersionId
# hasWip = $ServerRecipe.hasWip
# sourceCode = $ServerRecipe.sourceCode
# changelog = $ServerRecipe.changelog
# clonedFrom = $ServerRecipe.clonedFrom
# }

# ## Try the Request
# $response = Invoke-WebRequest -Method 'Post' -Uri $Uri -WebSession $TMSessionConfig.TMWebSession -Body $FormPostData
# if ($response.StatusCode -eq 200) {
# $responseContent = $response.Content | ConvertFrom-Json
# if ($responseContent.status -ne 'success') {
# Write-Error ('Unable to Publish Recipe:' + $responseContent.errors)
# }
# }
# }

function Invoke-TMRecipe {
    <#
    .SYNOPSIS
    Invokes a TransitionManager Recipe and produces a runbook.

    .DESCRIPTION
    This function allows a user to invoke a TransitionManager Recipe,
    choosing the Recipe, Bundles and Events related.

    .PARAMETER Name
    The name of the Recipe to use to Generate Tasks from

    .PARAMETER EventName
    The name of the Event to create tasks in

    .PARAMETER UseWip
    Determines if the Work In Progress recipe is used to generate tasks

    .PARAMETER PublishTasks
    Determines if the resulting tasks are published in the runbook or not.

    .PARAMETER ActivityId
    When Provided, This function will include Write-Progress Activities, using this ID as the root

    .PARAMETER ParentActivityId
    When Provided, This function will include Write-Progress Activities, using this ID as the Parent

    .EXAMPLE
    Invoke-TMRecipe -Name 'Migration Recipe' -EventName 'Move 1' -UseWip $True -PublishTasks $True

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [Alias('Recipe')]
        [String]$Name,

        [Parameter(Mandatory = $true)]
        [String]$EventName,

        [Parameter(Mandatory = $false)]
        [String[]]$Tags,

        [Parameter(Mandatory = $false)]
        [String]$TMSession = 'Default',

        [Parameter(Mandatory = $false)]
        [Switch]$PassThru,

        [Parameter(Mandatory = $false)]
        [Switch]$UseWip,

        [Parameter(Mandatory = $false)]
        [Switch]$PublishTasks,

        [Parameter(Mandatory = $false)][Int16]$ActivityId,
        [Parameter(Mandatory = $false)][Int16]$ParentActivityId = -1

    )

    begin {

        ## Get Session Configuration
        $TMSessionConfig = $global:TMSessions[$TMSession]
        if (-not $TMSessionConfig) {
            Write-Host 'TMSession: [' -NoNewline
            Write-Host $TMSession -ForegroundColor Cyan
            Write-Host '] was not Found. Please use the New-TMSession command.'
            Throw 'TM Session Not Found. Use New-TMSession command before using features.'
        }
    }

    process {

        ## Get the Recipe indicated
        $Recipe = Get-TMRecipe -Name $Name -TMSession $TMSession
        if (!$Recipe) {
            throw ("Recipe [$Name] does not exist.")
        }

        ## Resolve usage of the UseWip switch
        $FinalUseWip = $UseWip.IsPresent
        if ($UseWip.IsPresent -and !$Recipe.hasWip) {

            ## Change to use the Released version
            Write-Verbose ('Recipe ' + $Recipe.name + ' does not have a WIP version. Creating Tasks with the released version instead.')
            $FinalUseWip = $False
        }

        ## Get the required Event
        $TMEvent = Get-TMEvent -Name $EventName
        if (!$TMEvent) {
            New-TMEvent -Name $EventName
        }

        ## Find any associated tags
        $IncludeTags = Get-TMTag -TMSession $TMSession | Where-Object {
            $_.name -in $Tags
        }

        ## Confirm the Recipe and Event
        Write-Verbose 'Recipe and Event are valid. Generating Tasks...'

        # Update the newly created recipe with the data
        $uri = 'https://'
        $uri += $TMSessionConfig.TMServer
        $uri += '/tdstm/ws/task/generateTasks'

        ## Create the Post Body
        $PostBody = [PSCustomObject]@{
            recipeId        = $Recipe.recipeId
            recipeVersionId = $Recipe.recipeVersionId
            deletePrevious  = $true
            useWIP          = $FinalUseWip
            autoPublish     = ($PublishTasks.IsPresent) ?? $False
            eventId         = $TMEvent.id
            tag             = $IncludeTags.id -as [array]
        } | ConvertTo-Json -Compress

        ## Set the right content type
        Set-TMHeaderContentType -ContentType 'JSON'
        Set-TMHeaderAccept -Accept 'JSON'

        ## Make the request
        try {
            $response = Invoke-WebRequest -Method Post -Uri $uri -Body $PostBody -WebSession $TMSessionConfig.TMWebSession
        } catch {
            throw $_
        }

        ## Ensure a useful response came back
        if ($response.StatusCode -eq 200) {
            $responseContent = $response.Content | ConvertFrom-Json

            if ($responseContent.status -ne 'success') {

                throw ('The recipe could not be run: ' + $responseContent.errors)
            }
        }
        ## Get the Job ID for the Task Generation
        $TaskGenerationJobId = $responseContent.data.jobId

        ## With the file uploaded, Initiate the Datascript on the server
        $uri = 'https://'
        $uri += $TMSessionConfig.TMServer
        $uri += "/tdstm/ws/progress/$TaskGenerationJobId"

        Set-TMHeaderContentType -ContentType JSON -TMSession $TMSession

        ## The Recipe Generation Job has started, monitor the status
        if ($ActivityId) {
            Write-Progress -Id ($ActivityId + 1) -ParentId $ActivityId -Activity 'Task Generation Started' -CurrentOperation 'Starting Datascript Processing' -PercentComplete 5
        } else {
            Write-Verbose 'TransitionManager Task Generation: Starting Generating Tasks'
        }

        ## Poll for the status of the Task Generation
        ## TODO: This should be converted to a function for polling the job engine. It's nearly dupilcated now in the Import Batch watching.
        $Completed = $false
        while ($Completed -eq $false) {

            ## Check the status of the TaskGeneration Job
            try {

                $response = Invoke-WebRequest -Method Get -Uri $uri -WebSession $TMSessionConfig.TMWebSession
            } catch {
                throw $_.Exception.Message
            }

            ## Check the status of the script
            if ($response.StatusCode -eq 200) {
                $responseContent = $response.Content | ConvertFrom-Json
                if ($responseContent.status -eq 'success') {
                    $TaskGenerationProgress = $responseContent.data

                    switch ($TaskGenerationProgress.status) {
                        'Queued' {

                            $CurrentOperation = 'Task Generation Queued'
                            $Status = 'Queued'
                            $ProgressString = 'Status - Queued: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp
                            $SleepSeconds = 2
                            Break

                        }
                        'Pending' {
                            $CurrentOperation = 'Task Generation Pending'
                            $Status = 'Pending'
                            $ProgressString = 'Status - Pending: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp
                            $SleepSeconds = 2
                            Break
                        }
                        'Processing' {
                            $CurrentOperation = 'Task Generation Running'
                            $Status = 'Generating Tasks'
                            $ProgressString = 'Status - Running: ' + $TaskGenerationProgress.percentComp + '%'
                            $PercentComplete = $TaskGenerationProgress.percentComp
                            $SleepSeconds = 2
                            Break
                        }
                        'COMPLETED' {
                            $TaskGenerationJobId = $TaskGenerationProgress.detail
                            $CurrentOperation = 'Task Generation Complete'
                            $Status = 'Task Generation Complete'
                            $SleepSeconds = 0
                            $PercentComplete = 99
                            $ProgressString = 'Status - Task Generation Complete Complete.'
                            $Completed = $true
                            Break
                        }
                        'Failed' {
                            $CurrentOperation = 'Failed'
                            $Status = $TaskGenerationProgress.status
                            Write-Host 'Task Generation Failed '$TaskGenerationProgress.detail
                            Throw $TaskGenerationProgress.detail
                        }
                        Default {
                            $CurrentOperation = 'State Unknown'
                            $Status = 'Unknown. Sleeping to try again.'
                            $ProgressString = 'Unknown Status: ' + $TaskGenerationProgress.status
                            $PercentComplete = 99
                            $SleepSeconds = 2
                            Break
                        }
                    }

                    ## Notify the user of the Datascript Progress
                    if ($ActivityId) {
                        Write-Progress -Id ($ActivityId + 1) `
                            -ParentId $ActivityId `
                            -Activity 'Task Generation' `
                            -CurrentOperation $CurrentOperation `
                            -Status $Status `
                            -PercentComplete $PercentComplete
                    } else {
                        Write-Host $ProgressString
                    }
                }
            }

            ## Sleep a few seconds to allow the process to complete
            Start-Sleep -Seconds $SleepSeconds
        }

        ## DEBUGGING
        Write-Host $TaskGenerationJob

    }
}