Why Am I Getting Errors with Start-ThreadJob and Using Variables?

0
0
Asked By CuriousCabbage24 On

I'm trying to use Start-ThreadJob with my PowerShell profile, but I'm running into errors. Specifically, when I run this command:
```
$job=Start-ThreadJob -name maya6 -InitializationScript {. $using:profile} -ScriptBlock {ichild}
```
I get the following error:
'InvalidOperation: A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScripts in the script workflow...'
Also, when I tried to run:
```
$job=start-threadJob {. $args ; ichild} -ArgumentList $profile
```
It just freezes up my prompt when using `receive-job $job`, showing some bug reporting prompts. I figured that `using` was meant for this command, but it doesn't seem to work. I'm on PowerShell 7.4. Let me know if there's a fix or a better way to approach this!

4 Answers

Answered By DevDan78 On

Yeah, you might want to ditch using `$profile` altogether. It's just not portable, and jobs run without access to your normal session variables. Creating a module is definitely the way to go. Keep your job scripts clean, and I promise it'll save you a ton of headache down the line.

Answered By ScriptSavant99 On

Looks like you're running into issues because `$using:` doesn't work with `-InitializationScript` in `Start-ThreadJob`. It’s limited to the `-ScriptBlock`. The job doesn’t recognize the `$profile` variable frankly, since it runs in a different context. Instead, try this to run your profile inside the script block:
```
Start-ThreadJob -ScriptBlock { . $using:profile; ichild } |
Receive-Job -Wait
```
This way, you'll load the profile correctly when needed. If you plan to call this multiple times, consider creating a script block first and passing that in to keep things neat.

Answered By TechGuru88 On

I agree, `$using:` is kinda tricky! Using your profile isn't the way to go; it's meant to customize your environment, not run scripts from within it. Each job runs in its own separate runspace, so you'll need to prepare the worker's environment first. You might want to create modules for your scripts instead, and use `Import-Module` inside your script blocks for ease.

Answered By AsyncNinja42 On

Definitely consider looking into synchronized variables instead of using `$using:`. It might fit your needs better and keep things simpler! Just remember to keep it clean and focused.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.