PowerShell / PowerShell/PowerShell

Start-Job -InitializationScript should support $using: variable references too

Open
#4,530 9 comments 11 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue-Bug KeepOpen Up-for-Grabs WG-Cmdlets WG-NeedsReview
Dominant language
C#
Stars
55.5k
Forks
8.5k
Avg merge
1d 2h
Merged PRs (30d)
88

Description

Note:

  • The bug equally affects Start-ThreadJob.

In the script block passed to the (implied as the 1st positional) -ScriptBlock parameter of Start-Job, it is possible to reference variables from the calling scope via the $using: scope; e.g.:

# Make the background job's working directory the same as the calling session's and
# print the then-current location.
Start-Job { Set-Location $using:PWD; $PWD } | Receive-Job -Wait -AutoRemove

By contrast, the following - even though I'd expect it to be equivalent - does NOT work, because the $using: reference is in the -InitializationScript script block:

Start-Job -InitializationScript { Set-Location $using:PWD }  { $PWD } | Receive-Job -Wait -AutoRemove

Invocation fails with the following error messages:

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.
....

Note that the above command would be the cleanest workaround for not having a -WorkingDirectory parameter (see #4287) to set the working directory explicitly.

Both script blocks execute in the job's session, so they should both support $using: variable references.

Environment data

PowerShell Core v6.0.0-beta.5 on macOS 10.12.6
PowerShell Core v6.0.0-beta.5 on Ubuntu 16.04.3 LTS
PowerShell Core v6.0.0-beta.5 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)
Windows PowerShell v5.1.15063.483 on Microsoft Windows 10 Pro (64-bit; v10.0.15063)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the two commands using Start-Job and Start-ThreadJob, comparing $using: behavior in -ScriptBlock and -InitializationScript. Trace the job initialization entry points in the PowerShell implementation; done means both script blocks can resolve calling-scope $using: references without the reported error.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, powershell
Domain
cli
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.