Starting a remote job

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of marius marius 2 months, 3 weeks ago.

  • Author
    Posts
  • #68131
    Profile photo of marius
    marius
    Participant

    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

  • #68133
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #68226
    Profile photo of marius
    marius
    Participant

    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

You must be logged in to reply to this topic.