2

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?

Mark
  • 11,257
  • 11
  • 61
  • 97

2 Answers2

2

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
0

UPDATED:

I came across this code example:

http://blog.brianhartsock.com/2010/05/22/a-better-start-job-cmdlet/

Rather than a ScriptBlock, to use the FilePath parameter, I modified it as such:

param([string]$file)

$filePath = split-path $file -parent
Start-Job -Init ([ScriptBlock]::Create("Set-Location $filePath")) -FilePath $file -ArgumentList $args

This would be called as:

Start-JobAt c:\full_path\to\file\my_script.ps1 ($v1, $v2, $v3)

Using -Init (-InitializationScript) and firing off the Set-Location moves the current executing process to the directory of the script, so, from there you can determine relative location.

As the blog post mentions, you could have this as an external script (I tested mine as Start-JobAt.ps1) or make it part of your user/service account's profile.

David R. Longnecker
  • 2,897
  • 4
  • 29
  • 28