'using:' and other methods not working with start-threadJob to load objects into job session

running the following returns an error:
$job=Start-ThreadJob -name maya6 -InitializationScript {. $using:profile} -ScriptBlock {ichild} #this is an alias defined in the profile
error:
InvalidOperation: A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer.
ichild: The term 'ichild' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
I also tried:
$job=start-threadJob {. $args ; ichild} -ArgumentList $profile #ichild is an alias defined in my profile
and when I use receive-job $job
it freezes my prompt and I keep getting the following error:
Oops, something went wrong.
Please report this bug with ALL the details below, including both the 'Environment' and 'Exception' sections.
Please report on GitHub: https://github.com/PowerShell/PSReadLine/issues/new?template=Bug_Report.yaml
Thank you!
### Environment
PSReadLine: 2.3.4
PowerShell: 7.4.6
OS: Microsoft Windows 10.0.26100
BufferWidth: 170
BufferHeight: 21
Last 49 Keys:
I thought using
was for specifically this commandlet...
am on pwsh7.4
Answer
You're seeing a long-standing bug - see Read more - that was initially reported in 2017, which affects both Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) and PowerShell (Core) 7 as of v7.5.0; it has received no attention since then, unfortunately:
In short:
Start-Job
as well as well asStart-ThreadJob
unexpectedly do not support$using:
references in script blocks passed to the-InitializationScript
parameter.
Workarounds:
Either: Add the code you meant to pass to
-InitializationScript
to the main script block passed to the-ScriptBlock
parameter, where$using:
references are supported; applied to your case:Start-ThreadJob -ScriptBlock { . $using:profile; ichild } -name maya6
Or: If feasible, use string interpolation to "bake" the values from the caller's scope into a string from which you can create a script block; applied to your case:
Start-ThreadJob -InitializationScript ([scriptblock]::Create(". `"$profile`"")) -ScriptBlock { ichild } -name maya6
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles