Mark
Mark

Reputation: 11740

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?

Upvotes: 2

Views: 801

Answers (2)

David R. Longnecker
David R. Longnecker

Reputation: 3157

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.

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201692

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

Upvotes: 2

Related Questions