UseUsingScopeModifierInNewRunspaces
Severity Level: Warning
Description
If a scriptblock is intended to be run in a new runspace, variables inside it should use the
$using:
scope modifier, or be initialized within the scriptblock. This applies to:
Invoke-Command
- Only with the ComputerName or Session parameter.Workflow { InlineScript {} }
Foreach-Object
- Only with the Parallel parameterStart-Job
Start-ThreadJob
- The
Script
resource in DSC configurations, specifically for theGetScript
,TestScript
andSetScript
properties.
How to Fix
Within the ScriptBlock, instead of just using a variable from the parent scope, you have to add the
using:
scope modifier to it.
Example
Wrong
$var = 'foo'
1..2 | ForEach-Object -Parallel { $var }
Correct
$var = 'foo'
1..2 | ForEach-Object -Parallel { $using:var }
More correct examples
$bar = 'bar'
Invoke-Command -ComputerName 'foo' -ScriptBlock { $using:bar }
$bar = 'bar'
$s = New-PSSession -ComputerName 'foo'
Invoke-Command -Session $s -ScriptBlock { $using:bar }
# Remark: Workflow is supported on Windows PowerShell only
Workflow {
$foo = 'foo'
InlineScript { $using:foo }
}
$foo = 'foo'
Start-ThreadJob -ScriptBlock { $using:foo }
Start-Job -ScriptBlock {$using:foo }
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for