Author Posts

April 6, 2017 at 3:02 pm

I need to start a job on a remote computer and make it terminate asynchronously.
In other words, after successfully establishing a remote session I want to start a job on the remote computer and let it go on even after the session is closed, because it can take a long time.
The code I wrote looks like:

#
# Here I create my remote session $my_session
#
invoke-Command -Session $my_session -ScriptBlock {
        $my_job = Start-Job -Name "remote job" -ScriptBlock {
            $my_logfile = "c:\myfolder\mylog.txt"
            $my_message = "I started"
            $my_message >> $my_logfile 
            
            $my_message = "I terminated"
            $my_message >> $my_logfile 
            }
       } 
#

Something must be wrong because I don't see any log created on the target server and the code in the scriptblock is simply terminated.
How can create a job so that it can be execuded and terminated asynchronously?
How can I see the reasons becose the job fails?
Regards
marius

April 6, 2017 at 3:04 pm

Yeah, won't work. Jobs run within the process, and once you close the session, the process ends – so, no job. What you want to do instead is set up a PSScheduledJob and have it run, like, a minute later or right then. Scheduled Jobs exist out-of-process, and persist their results to disk.

Your other alternative is to disconnect your session, which leaves it running, and then reconnect later to get your results. But a disconnected session will eventually time out and close.

April 7, 2017 at 10:57 am

Thank you for the usefull suggestion.
I made some tests and it workd fine.
However, I discovered that PSScheduledJob is available only since PowerShell 3, while I need to use PowerShell 2.0: any other idea?
Regards
marius