lib/TMD.SessionManager.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781



<#
    This SessionManager Script handles creating and receiving output from a Session-Based Runspace Environment
    
    !!!!! Important Note !!!!!
    Electron/Node invokes this file to run a Session Manager.
    The primary purpose is as the primary interface between Electron and PowerShell.

    Additionally, this file is invoked directly by a forked process which has a StdOut handle/pipe open
    back towards TMD's UI (Via Electron -> Node -> Angular -> PowerShell Service: Receives Raised event)

    As a result, it is critical that any Standard Output (Write-Host, Strings, objects, pipeline stuff, etc) be
    carefully created using a contrived tokenized format. Here's an example of live output

    TMDTaskId_246269||Info||{"Message":"This loop has run 2 times","NoNewLine":false,"ForegroundColor":null,"BackgroundColor":null}
    TMDTaskId_246269||Progress||{"ActivityId":2,"ParentActivityId":-1,"Activity":"Loop 2","StatusDescription":"Processing","CurrentOperation":null,"PercentComplete":100,"SecondsRemaining":-1,"RecordType":1}
    TMDTaskId_246269||Info||{"Message":"This loop has run 3 times","NoNewLine":false,"ForegroundColor":null,"BackgroundColor":null}
    TMDTaskId_246269||Progress||{"ActivityId":3,"ParentActivityId":-1,"Activity":"Loop 3","StatusDescription":"Processing","CurrentOperation":null,"PercentComplete":100,"SecondsRemaining":-1,"RecordType":1}
    TMDTaskId_246269||Info||{"Message":"This loop has run 4 times","NoNewLine":false,"ForegroundColor":null,"BackgroundColor":null}
    TMDTaskId_246269||Progress||{"ActivityId":4,"ParentActivityId":-1,"Activity":"Loop 4","StatusDescription":"Processing","CurrentOperation":null,"PercentComplete":100,"SecondsRemaining":-1,"RecordType":1}
    TMDTaskId_246269||Info||{"Message":"This loop has run 5 times","NoNewLine":false,"ForegroundColor":null,"BackgroundColor":null}
    TMDTaskId_246269||Progress||{"ActivityId":5,"ParentActivityId":-1,"Activity":"Loop 5","StatusDescription":"Processing","CurrentOperation":null,"PercentComplete":100,"SecondsRemaining":-1,"RecordType":1}
    TMDTaskId_246269||Info||{"Message":"This loop has run 6 times","NoNewLine":false,"ForegroundColor":null,"BackgroundColor":null}
    TMDTaskId_246269||Progress||{"ActivityId":6,"ParentActivityId":-1,"Activity":"Loop 6","StatusDescription":"Processing","CurrentOperation

    TMDTaskId_246269||Completed

    Among others. There is "Info", "Started", "Failed", "Progress" and "Completed"
    Each of the JSON representations are of the associated PowerShell Primative Classes that are emitted by the the script using:

    - Started:
        Psuedo message, not actually created by PowerShell, it's written to the StdOut as early as possible (when this script gets the ID for the first time

    - Info: Write-Host or any pipeline output (Get-Date, for example)

    - Progress: Write-Progress
        ActivityID (Id)
        ParentActivityId
        Activity
        CurrentOpperation
        Status
        PercentComplete
        SecondsRemaining
        RecordType (1 = running, 0=Completed)
    
    - Errors Writtn as "Failed"
        - Errors Thrown from Infrastructure problems (Session issues, network, etc)
        - TM Action Scripts are run by the user are in a try catch and reported this way

    - Completed:
        Occurs when the Action Script provided by TM is completed, with no errors

    --- TODO
    - Verbose
        Write-Verbose output should be displayed in TMD as well (with a UI switch)

 #>


Function Start-TMDSessionManager {
    <#
    .SYNOPSIS
        Executes a new TMDSessionManager instance to handle invocation of TMD Client interaction
     
    .NOTES
        Name: Start-TMDSessionManager
        Author: TransitionManager
        Version: 1.0
        DateCreated: 2021-04-05
     
     
    .EXAMPLE
        Start-TMDSessionManager
     
     
    .LINK
        https://support.transitionmanager.net
    #>

    param(
        [Parameter(mandatory = $false)]
        [bool]$OutputVerbose = $false,
        # [bool]$OutputVerbose = $true,
    
        [Parameter(mandatory = $false)]
        [Int16]$PollSleepMs = 150,
    
        [Parameter()][Bool]$AllowInsecureSSL = $False,
        [Parameter()]$HostPID = 0
    )

    Begin {
        
        ## Enable Verbose Output if OutputVerbose was true
        if ($OutputVerbose) { 
            $Global:VerbosePreference = 'Continue'    
        }
        
        Write-Verbose -Message 'Starting SessionManger in '$PSCmdlet.ParameterSetName' Mode'
        Write-Verbose -Message ($MyInvocation.BoundParameters | ConvertTo-Json)
        ##
        ## Perform Configuration Validation/Setup
        ##
        
        ## Standardize access to the important Paths
        if ($OutputVerbose) { 
            $Global:VerbosePreference = 'Continue'    
            Write-Host 'VERBOSE: Checking TMD PsSession Configuration' 
        }
        Test-TMDPSSessionConfiguration
        
        ##
        ## Begin Running the Session Manager
        ##
      
        ## Allow the TMD Watcher script to continue and move past any transient errors
        $ErrorActionPreference = 'Continue' ## PRODUCTION = 'Continue'. Setting this to 'Stop' is useful in debugging this script
    
        ## Enable Verbose (using bool, not switch)
        if ($OutputVerbose) { 
        
            Write-Host "VERBOSE: PSSessionManager is running in Verbose Mode."
            $VerbosePreference = 'Continue' 
        
            ## If Host PID is present, notify that SessionManager is bound to that pid
            if ($HostPID -ne 0) {
                Write-Host "VERBOSE: Bound to TMD PID: $HostPID"
            }
        }
        else { 
            $VerbosePreference = 'SilentlyContinue' 
        }
        

        ## Create empty cache object
        $Global:LocalSessionCache = @{
            SessionManagerState = 'Connecting'
            LastJobEndTime      = Get-Date
        }
    
        ## Clear the TMD Queue and Debug Folders
        $QueueFiles = Get-ChildItem -Path $userPaths.queue -Recurse -File
        $DebugFiles = Get-ChildItem -Path $userPaths.debug -Recurse -File
 
        foreach ($QueueFile in $QueueFiles) {
            Remove-Item -Path $QueueFile -Force -Confirm:$false
        }
        foreach ($DebugFile in $DebugFiles) {
            Remove-Item -Path $DebugFile -Force -Confirm:$false
        }
      
        ## Connect and maintain a connection to the session
        $TmdUserSession = New-TMDPSSession
    
        #Check that we have a TMD Session for the user
        if (-not $TmdUserSession) {
            throw "Can't get a PSSession"
        }

        ## Add a RemoteSessionCache object to the remote Session
        Invoke-Command -Session $TmdUserSession -ScriptBlock {

            # Explicitly defining the RunSpace job statuses to look for when deciding
            # if the job should be removed
            New-Variable -Name FinishedJobStatuses -Force -Scope Global -Value @(
                [System.Management.Automation.PSInvocationState]::Failed
                [System.Management.Automation.PSInvocationState]::Stopped
                [System.Management.Automation.PSInvocationState]::Completed
            )
            
            # Create a session cache object to track jobs and their statuses
            New-Variable -Name RemoteSessionCache -Force -Scope Global -Value @{
                SessionManagerLastReport = ''
                RemoveJobAfter           = [PSCustomObject]@{}
            }
        }
    }

    Process {
        ## Run a continuous loop
        if ($OutputVerbose) { Write-Host 'VERBOSE: Starting Manager Monitoring Loop' }
        $Global:LocalSessionCache.SessionManagerState = 'Running'
        While ($Global:LocalSessionCache.SessionManagerState -eq 'Running') {
    
            ## Error Action
            $ErrorActionPreference = 'Continue'
    
            ## Connect to the Session when it's available
            Connect-PSSessionWhenReady $TmdUserSession | Out-Null
            
            ## Check on the Session Status
            if (-Not $TmdUserSession) {
                Write-Error 'PowerShell Session has errored!'
                $Global:LocalSessionCache.SessionManagerState = 'NotRunning'
            }

            ###
            ### Start Queued Action Requests
            ###
    


            ## Get Queued Action Requests - Use a Where-Object adds a second to the age to make sure the file is not in use
            $QueuedActionRequests = Get-ChildItem $userPaths.queue | Where-Object { ($_.LastAccessTime.AddSeconds(-1) -lt (Get-Date)) -and ($_.Extension -eq '.tmdar') }

            
            ## Invoke each of the Action Requests
            foreach ($QueuedActionRequest in $QueuedActionRequests) {
        
                ## Read the the Base64 Data
                $ActionRequest = Import-Clixml $QueuedActionRequest.FullName
        
                ## Remove the Queued item now that it has been read
                Remove-Item -Path $QueuedActionRequest.FullName -Force

                ## Add the HostPID to the ActionRequest
                Add-Member -InputObject $ActionRequest -NotePropertyName HostPID -NotePropertyValue $HostPID
           
                ## Start a new RS Job
                try {
                    Invoke-Command -Session $TmdUserSession -ArgumentList @($ActionRequest, $AllowInsecureSSL) -ScriptBlock {
                        param($ActionRequest, $AllowInsecureSSL)

                        ## Broker output
                        if ($ActionRequest.Broker) {
                            ## This is the first time the Action Request has been unwrapped inside the session, report update manually
                            $ProgressActivity = @{
                                ActivityId        = 0
                                ParentActivityId  = -1
                                Activity          = 'Starting Subject Task: ' + $ActionRequest.task.taskNumber + ' - ' + $ActionRequest.task.title
                                CurrentOpperation = 'Starting'
                                StatusDescription = ''
                                PercentComplete   = 5
                                SecondsRemaining  = -1
                                RecordType        = 0
                            } | ConvertTo-Json -Compress
                            ('TMDTaskId_' + $actionRequest.Broker.id + '||Progress||' + $ProgressActivity)
                        }


                        ## This is the first time the Action Request has been unwrapped inside the session, report update manually
                        $ProgressActivity = @{
                            ActivityId        = 0
                            ParentActivityId  = -1
                            Activity          = 'Starting Task: ' + $ActionRequest.task.taskNumber + ' - ' + $ActionRequest.task.title
                            CurrentOpperation = 'Starting'
                            StatusDescription = ''
                            PercentComplete   = 5
                            SecondsRemaining  = -1
                            RecordType        = 0
                        } | ConvertTo-Json -Compress

                        # Create a Progress Item Back to Angular
                        ('TMDTaskId_' + $actionRequest.task.id + '||Progress||' + $ProgressActivity)

                        ## Before Starting the RSJob, Make sure the Provider Module is imported into
                        ## this TMD session so it's loaded and available to supply to any future Provider Tasks
                        ## Include TMD and TM, and add any provider modules
                        $ModulesToImport = @('TMD.Common', 'TransitionManager')
     
                        ## Add Any Provider modules required
                        if ($ActionRequest.ProviderSetup.ModulesToImport) {
                            $ModulesToImport += $ActionRequest.ProviderSetup.ModulesToImport
                        }
     
                        ## Create an appropriate Runspace Name
                        $TmdPsRunspaceName = [String]('TMDTaskId_' + $ActionRequest.task.id + "_" + (Get-Date -Format 'FileDateTimeUniversal'))
     
                        ## Prepare the Runspace Job Options
                        $RSJobParams = @{
                            Name            = $TmdPsRunspaceName
                            ArgumentList    = @($ActionRequest, $AllowInsecureSSL)
                            ModulesToImport = $ModulesToImport
                            ScriptBlock     = {
                                param($ActionRequest, $AllowInsecureSSL)
                                try {
                        
                                    ## Provider Setup Startup Script
                                    if ($ActionRequest.ProviderSetup.StartupScript) {
                                        $ProviderStartupScript = [scriptblock]::Create($ActionRequest.ProviderSetup.StartupScript)
                                        Invoke-Command -NoNewScope -ScriptBlock $ProviderStartupScript
                                    }

                                    ## Create a ScriptBlock from the Action Script
                                    $ActionScriptBlock = [scriptblock]::Create($ActionRequest.options.apiAction.script)
                                    New-Variable -Name Params -Scope Global -Value $ActionRequest.params
                            
                                    ## Add $Credential if there is one
                                    if ($ActionRequest.PSCredential) {
                                        New-Variable -Scope Global -Name Credential -Value $ActionRequest.PSCredential
                                    }

                                    ## Wrap the user's script in a try/catch
                                    ## Invoke the User Script block
                                    Invoke-Command -ScriptBlock $ActionScriptBlock -ErrorAction 'Stop' -NoNewScope
                           
                                    ## Create a Data Options parameter for the Complete-TMTask command
                                    $CompleteTaskParameters = @{}

                                    ## Check the Global Variable for any TMAssetUpdates to send to TransitionManager during the task completion
                                    if ($Global:TMAssetUpdates) {
                                        $CompleteTaskParameters = @{ 
                                            Data = @{
                                                assetUpdates = $Global:TMAssetUpdates
                                            }
                                        }
                                    }

                                    ## Add SSL Exception if necessary
                                    if ($AllowInsecureSSL) {
                                        $CompleteTaskParameters | Add-Member -NotePropertyName 'AllowInsecureSSL' -NotePropertyValue $True
                                    }
                                 
                                    ## Complete the TM Task, sending Updated Data values for the task Asset
                                    if ($ActionRequest.HostPID -ne 0) {
                                        Complete-TMTask -ActionRequest $ActionRequest @CompleteTaskParameters
                                    }
                        
                                    ## Complete the root activity to provide a consistent experience for all tasks
                                    $CompleteProgressActivity = @{
                                        Id               = 0
                                        ParentId         = -1
                                        Activity         = 'Task Complete: ' + $ActionRequest.task.taskNumber + ' - ' + $ActionRequest.task.title
                                        PercentComplete  = 100
                                        SecondsRemaining = -1
                                        Completed        = $True
                                    }
                                    Write-Progress @CompleteProgressActivity
                            
                                }
                                catch {
                           
                                    ## Get the Exception message
                                    $ExceptionMessage = $Error.Exception.Message
                                                        
                                    ## Send the Error Message (Only send if TMD started the process)
                                    if ($ActionRequest.HostPID -ne 0) {
                                        Set-TMTaskOnHold -ActionRequest $ActionRequest -Message ('Action Error: ' + $ExceptionMessage)
                                    }

                                    ## Throw the full error message
                                    Write-Error $_
                                    Throw $ExceptionMessage
                                }

                            }
                        }
                
                        ## Start the RS Job
                        Start-RSJob @RSJobParams | Out-Null
                    }
     
                
            
                }
                catch {
                    Write-Host 'VERBOSE: '$_
                }
            }
   
            ###
            ### Collect Output from Sessions/Runspaces
            ###
            try {
                ## Collect the output of each runspace
                [Array]$TaskRunspaces = Invoke-Command -Session $TmdUserSession -ScriptBlock {
        
                    ## Disable Error Stops so we can receive the data back and continue running
                    $ErrorActionPreference = 'Continue'
        
                    ## Get the Runspaces in the Remote Session
                    $RunspaceJobs = Get-RSJob

                    ## Connect to each Runspace and create a report of it's status
                    $RunspaceReports = [System.Collections.ArrayList] @()
                    foreach ($RunspaceJob in $RunspaceJobs) {
        
                        ## Create the TaskIdString used to report status to TMD
                        $TaskIdString = ($RunspaceJob.Name.split('_') | Select-Object -First 2) -join ('_')

                        ## Disable Error Throws so we can receive the data back and handle it conditionally
                        $ErrorActionPreference = 'Continue'

                
                        ## Check for Errors and get the Error String
                        # Write-Host 'ERROR ERROR ERROR: ErrorItem has Exception'
                        if ($RunspaceJob.HasErrors) {
                    
                            ## Create an array of strings to return
                            $ErrorStrings = [System.Collections.ArrayList]@()
                    
                            ## Iterate over each Error in the Runspace Error list
                            foreach ($ErrorItem in $RunspaceJob.Error) {
                        
                                ## Not all Errors have an Exception node, it may just be a text Error
                                if ($ErrorItem.Exception) {
                            
                                    ## Exceptions might be an exception, or an error record.
                                    if ($ErrorItem.Exception.Message) {
                                        # Write-Host 'ERROR ERROR ERROR: ErrorItem has Exception.Message'$ErrorItem.Exception.Message
                                        $ErrorStrings.Add($ErrorItem.Exception.Message) | Out-Null
                                    }
                                    elseif ($ErrorItem.Exception.ErrorRecord) {
                                        # Write-Host 'ERROR ERROR ERROR: ErrorItem has Exception.Message'$ErrorItem.Exception.ErrorRecord
                                        $ErrorStrings.Add($ErrorItem.Exception.ErrorRecord) | Out-Null
                                    }
                                    else {
                                        # Write-Host 'ERROR ERROR ERROR: ErrorItem is not a known exception type'$ErrorItem.Exception.toString()
                                        $ErrorStrings.Add($ErrorItem.Exception.ToString()) | Out-Null
                                    }
                                }
                                else {
                                    # Write-Host 'ERROR ERROR ERROR: ErrorItem does NOT have an Exception'
                                    $ErrorStrings.Add('Unhandled Error. No error message returned from the process.') | Out-Null
                                }
                        
                                ## With an Exception Thrown, Mark the job for removal immediately
                                if ($ErrorStrings.Count -gt 0) {
                            
                                    ## Add a removal timestamp of now so the job is removed on this pass
                                    $Global:RemoteSessionCache.RemoveJobAfter | Add-Member -NotePropertyName $TaskIdString -NotePropertyValue (Get-Date) -Force
                                }
                            }
                        }
                
                        ## Return a formatted object back for SessionManager to interpret and process without using the session
                        ## Parts of this Object are piped into a ConvertTo-JSON so they are snapped and no live items are returned.
                        $RunspaceReport = @{
                            Type         = 'RunspaceReport'
                            TaskIdString = $TaskIdString; 
                            Runspace     = @{
                                Guid      = $RunspaceJob.InstanceId
                                <#
                                RunspaceJob States
                                https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.psinvocationstate?view=powershellsdk-7.0.0
                                
                                ENUMS
                                ==================
    
                                Completed 4 PowerShell has completed executing a command.
                                Disconnected 6 PowerShell is in disconnected state.
                                Failed 5 PowerShell completed abnormally due to an error.
                                NotStarted 0 PowerShell has not been started
                                Running 1 PowerShell is executing
                                Stopped 3 PowerShell is completed due to a stop request.
                                Stopping 2 PowerShell is stoping execution.
                        #>

                                State     = $RunspaceJob.State
                                HasErrors = $RunspaceJob.HasErrors
                                Output    = $RunspaceJob.Output
                                Errors    = $ErrorStrings
                            
                                ## Stream objects have too much information lost when they are passed from the session back to the Session Manager.
                                ## Convert them to JSON and return them as structured text.
                                Streams   = @{
                                    Information = $RunspaceJob.InnerJob.Streams.Information | ConvertTo-Json -Compress -ErrorAction 'SilentlyContinue'
                                    Progress    = $RunspaceJob.InnerJob.Streams.Progress | ConvertTo-Json -Compress -ErrorAction 'SilentlyContinue'
                                    Verbose     = $RunspaceJob.Verbose #| ConvertTo-Json -Compress -ErrorAction 'SilentlyContinue')
                                    Debug       = $RunspaceJob.Debug #| ConvertTo-Json -Compress -ErrorAction 'SilentlyContinue')
                                    Warning     = $RunspaceJob.Warning #| ConvertTo-Json -Compress -ErrorAction 'SilentlyContinue')
                                }
                            }
                        } | ConvertTo-Json -Compress
                
                        ## Add the JSON Runspace Report to the Runspace Queue
                        $RunspaceReports.Add($RunspaceReport) | Out-Null
            
                        ## Clear the Output Queue and Streams
                        if ($RunspaceJob.HasMoreData) {
                            ## Clear the Output Queue
                            $RunspaceJob | Receive-RSJob | Out-Null
                        }

                        ## Clear the Output Streams
                        $RunspaceJob.InnerJob.Streams.ClearStreams()

                        ## Add a debug token
                        # $RunspaceReports.Add((@{
                        # Type = 'DebugReport'
                        # Message = ('Checking Status of Runspace ' + $TaskIdString + ', Runspace.State ' + $RunspaceJob.State)
                        # } | ConvertTo-Json -Compress)) | Out-Null
                
                        ## Mark the Job for removal. This allows for the data to be collected before the job is removed at the end of this loop
                        ## Failed = 5, Completed = 4
                        if (($RunspaceJob.State -in $FinishedJobStatuses) -and (-Not $RunspaceJob.HasMoreData)) {
                    
                            ## Check the RemoteSessionCache list for this existing JobId
                            if ($Global:RemoteSessionCache.RemoveJobAfter.PSObject.Properties.Name -notcontains $TaskIdString) {
                        
                                ## Create a RemoveAfter timestamp
                                $RemoveAfter = (Get-Date).AddSeconds(1)
                                $Global:RemoteSessionCache.RemoveJobAfter | Add-Member -NotePropertyName $TaskIdString -NotePropertyValue $RemoveAfter
                    
                                # ## Add a debug token
                                # $RunspaceReports.Add(([PSCustomObject]@{
                                # Type = 'DebugReport'
                                # Message = ('Marking Task ID ' + $TaskIdString + ' for removal at ' + $RemoveAfter)
                                # } | ConvertTo-Json -Compress)) | Out-Null
                            }
                        }

                        ## Check the RemoteSessionCache list for this existing JobId
                        if ($Global:RemoteSessionCache.RemoveJobAfter.PSObject.Properties.Name -contains $TaskIdString) {
                    
                    
                            ## Get the timestamp details of when the Job can be removed
                            $PermittedRemovalTimestamp = $Global:RemoteSessionCache.RemoveJobAfter.$TaskIdString
                            $TimeUntilRemoval = New-TimeSpan -Start (Get-Date) -End $PermittedRemovalTimestamp
                    
                            # ## Add a debug token
                            # $RunspaceReports.Add(([PSCustomObject]@{
                            # Type = 'DebugReport'
                            # Message = ('Checking Task ID ' + $TaskIdString + ' if the removal time at ' + $RemoveAfter + ' is after ' + (Get-Date))
                            # } | ConvertTo-Json -Compress)) | Out-Null

                            ## Check the RemoveAfter timestamp
                            if ($TimeUntilRemoval.TotalSeconds -lt 0) {
                        
                                ## Remove the Runspace from the Session List
                                $Global:RemoteSessionCache.RemoveJobAfter.PSObject.Properties.Remove($TaskIdString)

                                if ($OutputVerbose) { Write-Host 'Removing Runspace Job: '$RunspaceJob.Id }

                                ## Remove the Runspace Job itself
                                Remove-RSJob $RunspaceJob | Out-Null

                                ## Create a Task End report
                                $TaskEndReport = @{
                                    Type         = 'TaskEndReport';
                                    TaskIdString = $TaskIdString; 
                                    State        = $RunspaceJob.State
                        
                                } | ConvertTo-Json -Compress
                                $RunspaceReports.Add($TaskEndReport) | Out-Null
                            }
                        }
    
                        ## Return any Runspace reports provided
                        $RunspaceReports
                    } 
                } 
            }
            catch {
                Write-Host 'VERBOSE: ' $_
            }
        
            ## Disconnect from the session so it can be connected to when invoking jobs
            ## Only for Windows, MacOS keeps a persistent SSH session open.
            if ($IsWindows) {
                Disconnect-PSSession -Session $TmdUserSession | Out-Null
            }

            ###
            ### Report Output from Individual Runspaces to TMD
            ###

            $ActiveTMDActions = 0
            ## For Each of Task Runspace, Collect, format and report the output
            foreach ($TaskRunspace in ($TaskRunspaces | ConvertFrom-Json -ErrorAction 'SilentlyContinue')) {
           
                ## Get the TaskIdString used for progress updates
                $TaskIdString = $TaskRunspace.TaskIdString
      
                # if ($OutputVerbose) { Write-Host 'VERBOSE Task Runspace Report Received' }
                # if ($OutputVerbose) { Write-Host 'VERBOSE Task Runspace Report Type: ' $TaskRunspace.Type }
                # if ($OutputVerbose) { $TaskRunspace | ConvertTo-Json | Write-Host }

                ## TaskRunspaceReports will be of type 'EndTaskReport' or 'RunspaceReport'
                switch ($TaskRunspace.Type) {

                    'DebugReport' {
                        If ($OutputVerbose) {
                            Write-Host 'VERBOSE PSSessionManagerRemote'  $TaskRunspace.Message
                        }
                    }

                    'RunspaceReport' {  
                   
                        ## Increment the ActiveTMDActions Counter
                        $ActiveTMDActions++

                        ## The output Pipeline is expectd to be an array of strings.
                        if ($TaskRunspace.Runspace.Output) {
           
                            ## Format the Info Token, using the same mechanism as above
                            $MessageDataJson = @{
                                Message         = $TaskRunspace.Runspace.Output
                                NoNewLine       = $false
                                ForegroundColor = 'White'
                                BackgroundColor = 'Black'
                            } | ConvertTo-Json -Compress

                            ## Format the TMD Output String
                            $OutputJSONString = ($TaskIdString + '||Info||' + $MessageDataJson)
                            Write-Host 'VERBOSE Runspace Output'  $OutputJSONString
                            
                            ## Return the String to the TaskOutput Array
                            Write-Host $OutputJSONString
                        }
                        
                        ## Convert the Information Stream, which is formatted as a JSON Array
                        ## For Each Information Message in the Output Stream
                        foreach ($Info in ($TaskRunspace.Runspace.Streams.Information | ConvertFrom-Json -ErrorAction 'SilentlyContinue')) {
                            # Convert to JSON so it can be properly interpreted by Angular
                            $TaskInfo = $Info.MessageData | ConvertTo-Json -Compress
                            
                            ## Prevent Blank Lines from being sent
                            if ($TaskInfo) {
                                
                                ## Format the Info Token
                                $InfoJSONString = ($TaskIdString + '||Info||' + $TaskInfo)
                                Write-Host 'VERBOSE InfoJSONString'  $InfoJSONString
                                # if (-not ($Global:LocalSessionCache.Tasks.$TaskIdString.contains($InfoJSONString))) {
                                    
                                ## Add the string to the cache
                                # $Global:LocalSessionCache.Tasks.$TaskIdString.Add($InfoJSONString) | Out-Null
                                    
                                ## Return the String to the TaskOutput Array
                                Write-Host $InfoJSONString
                                # }
                            }
                        }
                            
                        ## For Each Progress Item in the Progress Stream
                        foreach ($ProgressItem in ($TaskRunspace.Runspace.Streams.Progress | ConvertFrom-Json -ErrorAction 'SilentlyContinue')) {
                                
                            ## Get a JSON String
                            $TaskProgress = ($ProgressItem | ConvertTo-Json -Compress)
                            
                            ## Some poorly behaving tools ( or Authors :p ) will report negative percentages.
                            ## We'll use MS guidance and remove them from display ## https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.progressrecord.percentcomplete?view=pscore-6.2.0#System_Management_Automation_ProgressRecord_PercentComplete
                            ## Todo: Maybe we can leverage this into a 'Undetermined' percentage complete. We need something like that
                            if ($ProgressItem.PercentComplete -eq -1) {
                                continue
                            }
                            
                            #Filter out items not pertinent to TMD UI updates
                            # Invoke-WebRequest which is commonly used in scripts. it is very noisy, fortunatly it's consistent in it's behaviors.
                            # '* web request' is the 'Activity' every time.
                            if (@('Writing web request', 'Reading web request').Contains($ProgressItem.Activity)) {
                                continue
                            }
                            
                            $ProgressJSONString = ($TaskIdString + '||Progress||' + $TaskProgress)
                            Write-Host 'VERBOSE ProgressJSONString'  $ProgressJSONString
                            # if (-not ($Global:LocalSessionCache.Tasks.$TaskIdString.contains($ProgressJSONString))) {
                                
                            ## Add the string to the cache
                            # $Global:LocalSessionCache.Tasks.$TaskIdString.Add($ProgressJSONString) | Out-Null
                                
                            ## Return the Progress String to the TaskOutput Array
                            Write-Host $ProgressJSONString
                            # }
                        }

                        # TODO Build Debug, Verbose and Warning so they can be formatted and sent to TMD as well
                        # $StreamVerbose = $TaskRunspace.Runspace.Streams.Verbose
                        # $StreamDebug = $TaskRunspace.Runspace.Streams.Debug
                        # $StreamWarning = $TaskRunspace.Runspace.Streams.Warning
                        
                        ## If the Runspace has an error
                        if ($TaskRunspace.Runspace.HasErrors) {
                            
                            ## Error is an Array of strings formatted before being returned from the PS Session
                            foreach ($RunspaceError in $TaskRunspace.Runspace.Errors) {
                                
                                ## Remove unnecessary system details from the Error Message
                                $ErrorString = $RunspaceError `
                                    -replace 'System.Management.Automation.ParentContainsErrorRecordException\: ', '' `
                                    -replace 'Exception calling "EndInvoke" with "1" argument\(s\)\: "', '' `
                                    -replace '"$', '' `
                                    -replace "`r`n", ' '
                                
                                ## If the Thrown Message is not blank
                                if ($ErrorString) {
                                    
                                    ## Send the Error
                                    $ErrorJSONString = ($TaskIdString + '||Error||' + $ErrorString)
                                    Write-Host 'VERBOSE ErrorJSONString'  $ErrorJSONString
                                    
                                    ## Return the Progress String to the TaskOutput Array
                                    Write-Host $ErrorJSONString
                                }
                            }
                        } 
                    }
                    'TaskEndReport' {
                        
                        ## Update the last End timestamp in the Session Cache
                        $Global:LocalSessionCache.LastJobEndTime = Get-Date
                        switch ($TaskRunspace.State) {
                            5 {
                                ## Task Failed
                                Write-Host ($TaskIdString + '||Failed')
                                Write-Host 'VERBOSE Task Failed:'  $TaskIdString
                                break
                            }
                            4 {
                                ## Task Completed
                                Write-Host 'VERBOSE Task Completed:'  $TaskIdString
                                Write-Host ($TaskIdString + '||Completed')
                                break
                            }
                            Default {
                                Write-Host ($TaskIdString + '||Completed')
                            }
                        }
                    }
                }
            }
        
            ###
            ### Report Session Health and Runspace Count
            ###
    
            # Update the Session Manager Status, but check the cache to see if it's the same as the last reported status.
            # $TaskRunspaceCount = ($TaskRunspaces | Where-Object {$_.Type -eq 'RunspaceReport'}).Count
            $PsSessionManagerStatus = 'PSSessionManager||Status||Monitoring ' + $ActiveTMDActions + ' TMD Actions'
        
            ## Correct for Pluralization when there is a single Action
            if ($ActiveTMDActions -eq 1) { $PsSessionManagerStatus = $PsSessionManagerStatus -replace 'Actions', 'Action' }
        
            ## Report the Session update if it's not the same as the last one
            if ($Global:LocalSessionCache.SessionManagerLastReport -ne $PsSessionManagerStatus) {
          
                ## Provide a Service-Level sumamry monitoring for updating the UI
                $Global:LocalSessionCache.SessionManagerLastReport = $PsSessionManagerStatus
          
                ## Return the PS Session Manager Status to the TaskOutput Array
                Write-Host $PsSessionManagerStatus
            }

            ###
            ### Script Exit Stratagy
            ###

            ## Determine if the script should exit, based on the Jobs and the Host PID
            if ($HostPID -ne 0) {

                ## Determine if the Host TMD process is still running
                if (-not (Get-Process -Id $HostPID -ErrorAction 'SilentlyContinue')) {
                
                    ## Only exit if no jobs are present
                    if ($TaskRunspaces.Count -eq 0) {
                    
                        ## After the Last job has been done for 1 seconds
                        if ($Global:LocalSessionCache.LastJobEndTime -lt ((Get-Date).AddSeconds(-1))) {
                            $Global:LocalSessionCache.SessionManagerState = "Exit"
                        }
                    }
                }
            }
            else {
          
                ## Exit the SessionManager
                if ($TaskRunspaces.Count -eq 0) {

                    ## After the Last job has been done for 30 seconds
                    if ($Global:LocalSessionCache.LastJobEndTime -lt ((Get-Date).AddSeconds(-5))) {
                        $Global:LocalSessionCache.SessionManagerState = "Exit"
                    }
                }
            }

            ## Sleep a bit before checking again
            Start-Sleep -Milliseconds $PollSleepMs
            Continue

    
        } ## End of While :: Session Manager State is Connected
    }

    End {

        ## Disconnect and remove from the session
        if ($IsWindows) {
            Disconnect-PSSession -Session $TmdUserSession | Out-Null
        }
        Remove-PSSession -Session $TmdUserSession | Out-Null
    }
}