powershellpowershell-jobs

Is there any way to tell what script is running when started with start-job -filename?


I'm starting a PowerShell job with something like the following command:

start-job -filename my_script.ps1 -argumentlist ($v1, $v2, $v3)

This script, however needs to know where it's located, because it runs other commands based on their location relative to it. When run directly from the prompt, constructs such as these work:

join-path (split-path (& { $myinvocation.scriptname })) "relative path\filename"
join-path (split-path $myinvocation.mycommand.definition) "relative path\filename"

This doesn't work at all when started as a job as in the first example, however. How can I determine where I'm running from when I'm started as a job?


Solution

  • It appears to be like the remoting case where the file is passed into the job as a script block so the notion of which file the script came from gets lost. You could pass in the path as well (although that seems less than ideal):

    PS> gc .\job.ps1
    param($scriptPath)
    "Running script $scriptPath"
    PS> $job = Start-Job -FilePath .\job.ps1 -ArgumentList $pwd\job.ps1
    PS> Wait-Job $job
    
    Id  Name            State      HasMoreData     Location  Command
    --  ----            -----      -----------     --------  -------
    13  Job13           Completed  True            localhost param($scriptPath)...
    
    
    PS> Receive-Job $job.id
    Running script C:\Users\hillr\job.ps1