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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay