lib/TMD.SessionManager.ps1
<# 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 } } |