> ## 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/PSUseDeclaredVarsMoreThanAssignments

> Extra Variables

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

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

## Description

Variables that are assigned but not used are not needed.

<Note>
  For this rule, the variable must be used within the same scriptblock that it was declared or it
  won't be considered to be 'used'.
</Note>

## How

Remove the variables that are declared but not used.

## Examples

### Problematic code

```powershell theme={null}
function Test
{
    $declaredVar = 'Declared just for fun'
    $declaredVar2 = 'Not used'
    Write-Output $declaredVar
}
```

### Correct code

```powershell theme={null}
function Test
{
    $declaredVar = 'Declared just for fun'
    Write-Output $declaredVar
}
```

### Special cases

The following examples trigger the **PSUseDeclaredVarsMoreThanAssignments** warning. This behavior
is a limitation of the rule. There is no way to avoid these false positive warnings.

In this case, the warning is triggered because `$bar` is not used within the scriptblock where it
was defined.

```powershell theme={null}
$foo | ForEach-Object {
    if ($_ -eq $false) {
        $bar = $true
    }
}

if($bar){
    Write-Host 'Collection contained a false case.'
}
```

In the next example, the warning is triggered because `$errResult` isn't recognized as being used in
the `Write-Host` command.

```powershell theme={null}
$errResult = $null
Write-Host 'Ugh:' -ErrorVariable errResult
```

## Source

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