PowerShell / PowerShell/PowerShell
`using` statements aren't allowed in script-block literals, but are in script blocks created with `[scriptblock]::Create()`
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 55.5k
- Forks
- 8.5k
- Avg merge
- 1d 2h
- Merged PRs (30d)
- 88
Description
Prerequisites
- Write a descriptive title.
- Make sure you are able to repro it on the latest released version
- Search the existing issues.
- Refer to the FAQ.
- Refer to Differences between Windows PowerShell 5.1 and PowerShell.
Steps to reproduce
usingstatements 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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