Launching background tasks in a remote session that don't get killed when the session is removed Launching background tasks in a remote session that don't get killed when the session is removed powershell powershell

Launching background tasks in a remote session that don't get killed when the session is removed


Here is first an explanation of why it works so. Perhaps someone else can use it to bring a another solution.

I edited my answer with solution based on WMI.

When you enter a remote session :

PS C:\Users\JPB> enter-PSSession -ComputerName 192.168.183.100 -Credential $cred[192.168.183.100]: PS C:\Users\jpb\Documents>

You create on the server a process called wsmprovhost.exe as shown here under

enter image description here

When you simply start a process in this remote session :

[192.168.183.100]: PS C:\Users\jpb\Documents> Start-Process calc.exe

The new process is a child of wsmprovhost.exe as shown here under

enter image description here

If you stop the remote session wsmprovhost.exe disappeared and so the child process.

The explanation is that wsmprovhost.exe and all the processes started by this one belongs to the same job.

enter image description here

By default, on one hand this job DOES NOT supports JOB_OBJECT_LIMIT_BREAKAWAY_OK limit flag that does not allow us to start a process with CREATE_BREAKAWAY_FROM_JOB flag, on the other hand this job supports JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE limit flag that causes all processes associated with the job to terminate when the last handle to the job is closed.

It perhaps exists a solution to configure WinRM to support jobs which supports JOB_OBJECT_LIMIT_BREAKAWAY_OK.


Edited :

So reading Microsoft documentation, I found a documented technical way for you to start a program through WinRM but in an onother job. By default, processes created using CreateProcess by a process associated with a job are associated with the job; however, processes created using Win32_Process.Create are not associated with the job.

So if in you remote session you create a process with WMI like this :

PS C:\silogix> $ps = New-PSSession -ComputerName 192.168.183.100 -Credential $credPS C:\silogix> Enter-PSSession -Session $ps[192.168.183.100]: PS C:\Users\jpb\Documents> Invoke-WmiMethod -path win32_process -name create -argumentlist "calc.exe"__GENUS          : 2__CLASS          : __PARAMETERS__SUPERCLASS     :__DYNASTY        : __PARAMETERS__RELPATH        :__PROPERTY_COUNT : 2__DERIVATION     : {}__SERVER         :__NAMESPACE      :__PATH           :ProcessId        : 1236ReturnValue      : 0[192.168.183.100]: PS C:\Users\jpb\Documents> exitPS C:\silogix> Remove-PSSession $ps

If you stop the remote session wsmprovhost.exe disappeared, but the new process stay on the server as show here under :

enter image description here

The processes started with WMI does not belongs to any Job. In french I would say "Ce qu'il fallait démontrer"