PowerShell / PowerShell/PowerShell

`using` statements aren't allowed in script-block literals, but are in script blocks created with `[scriptblock]::Create()`

Open
#19,985 0 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs-Triage WG-Language
Dominant language
C#
Stars
55.5k
Forks
8.5k
Avg merge
1d 2h
Merged PRs (30d)
88

Description

Prerequisites
Steps to reproduce
  • using statements are disallowed in script-block literals, whereas
  • source code passed to [scriptblock]::Create() permits them.

I don't if there's a good reason not to allow them - at least a first glance, they seem to work as intended - but the inconsistency is worth resolving either way.

# Define a snippet of source code as  a string.
$sbText = 'using namespace System.Collections; [ArrayList]'

# OK script block created from string via [scriptblock]::Create()
& ([scriptblock]::Create($sbText))

# !! BROKEN: A script block *literal* with the same source code
# !!         doesn't permit `using` statements.
Invoke-Expression "& { $sbText }"
Expected behavior

Both script-block calls should succeed and output the [System.Collections.ArrayList] type.

Actual behavior

The 2nd call, based on a script-block literal, fails with A 'using' statement must appear before any other statements in a script.

Error details

No response

Environment data
PowerShell 7.4.0-preview.4
Visuals

No response

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

Start by reproducing the two examples in the issue: a script-block literal and one created with [scriptblock]::Create(). Compare how each handles the using statement and determine whether their behavior should be made consistent. Done means the documented examples agree and the expected ArrayList type output succeeds without the ordering error.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.