Remove Variable - PowerShell


Overview

The Remove-Variable command in PowerShell removes variables from the current scope. It is commonly used during script development or interactive sessions to clean up the variable namespace and manage memory usage.

Syntax

Remove-Variable [-Name] <Name> [-Scope <Scope>] [<CommonParameters>]

Options/Flags

  • -Name: (Required) Specifies a list of variable names to remove.
  • -Scope: (Optional) Specifies the scope of the variable to remove. Valid values are “Global”, “Script”, “Local”, or “Private”. Defaults to “Local”.

Examples

Removing a Single Variable:

Remove-Variable -Name myVariable

Removing Multiple Variables:

Remove-Variable -Name variable1, variable2, variable3

Removing Variables from a Specific Scope:

Remove-Variable -Name myVariable -Scope Global

Removing Unscoped Temporary Variables:

Remove-Variable -Name *

Common Issues

  • Variable Not Found: If the specified variable does not exist, Remove-Variable will return an error.
  • Access Denied: Attempting to remove a variable defined in a higher scope may result in an access denied error.

Integration

Remove-Variable can be combined with other commands to manage variables efficiently. For example:

  • Resetting Variables:
>$env:Path = ($env:Path -split ";") -join ";"  # Modify environment variable
Remove-Variable -Name Path  # Reset variable to default value
  • Cleaning Up Script Scope:
foreach ($variable in $PSVariableTable) {
    if ($variable.PSCustomAttribute -and $variable.PSCustomAttribute.Scope -eq "Script") {
        Remove-Variable -Name $variable.Name
    }
}
  • Get-Variable
  • New-Variable
  • Set-Variable