> ## Documentation Index
> Fetch the complete documentation index at: https://tally.wharflab.com/llms.txt
> Use this file to discover all available pages before exploring further.

# powershell/PSUseUsingScopeModifierInNewRunspaces

> Use 'Using:' scope modifier in RunSpace ScriptBlocks

`powershell/PSUseUsingScopeModifierInNewRunspaces` is a PSScriptAnalyzer diagnostic emitted by tally for PowerShell snippets embedded in Dockerfiles.

| Property | Value            |
| -------- | ---------------- |
| Severity | Warning          |
| Category | PSScriptAnalyzer |
| Auto-fix | No               |

## 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** parameter
* `Start-Job`
* `Start-ThreadJob`
* The `Script` resource in DSC configurations, specifically for the `GetScript`, `TestScript` and
  `SetScript` 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.

## Examples

### Problematic code

```powershell theme={null}
$var = 'foo'
1..2 | ForEach-Object -Parallel { $var }
```

### Correct code

```powershell theme={null}
$var = 'foo'
1..2 | ForEach-Object -Parallel { $using:var }
```

## More correct examples

```powershell theme={null}
$bar = 'bar'
Invoke-Command -ComputerName 'foo' -ScriptBlock { $using:bar }
```

```powershell theme={null}
$bar = 'bar'
$s = New-PSSession -ComputerName 'foo'
Invoke-Command -Session $s -ScriptBlock { $using:bar }
```

```powershell theme={null}
# Remark: Workflow is supported on Windows PowerShell only
Workflow {
    $foo = 'foo'
    InlineScript { $using:foo }
}
```

```powershell theme={null}
$foo = 'foo'
Start-ThreadJob -ScriptBlock { $using:foo }
Start-Job -ScriptBlock {$using:foo }
```

## Source

This rule documentation is adapted from Microsoft's PSScriptAnalyzer documentation for
[UseUsingScopeModifierInNewRunspaces](https://github.com/MicrosoftDocs/PowerShell-Docs-Modules/blob/main/reference/docs-conceptual/PSScriptAnalyzer/Rules/UseUsingScopeModifierInNewRunspaces.md),
licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
