DEV Community

taijidude
taijidude

Posted on • Edited on

3 3

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up