DEV Community

taijidude
taijidude

Posted on • Updated on

Background Jobs are not run at $PSScriptRoot

Stumbled over this one a while ago. While i was developing a script which started several background jobs, i was making the assumption that the jobs would be run in the same directory the "mother script" was in. But turns out this is not true, as we can see in the following example.

test.ps1:

Start-Job -name test1 -ScriptBlock {(Get-Location).Path}
Wait-Job -Name test1 -Timeout 120
Receive-Job -Name test1
Enter fullscreen mode Exit fullscreen mode

Image description

When you want to work with your script location, you can just pass it to your scriptblock via the argumentlist.

test2.ps1:

Start-Job -name test2 -ScriptBlock {Set-Location $args[0]; (Get-Location).Path} -ArgumentList $PSScriptRoot
Wait-Job -Name test2 -Timeout 120
Receive-Job -Name test2
Enter fullscreen mode Exit fullscreen mode

And the final output:

Image description

Top comments (0)