Clear Variable - PowerShell


The Clear-Variable command in PowerShell removes one or more variables from the current scope. It allows you to delete unnecessary or outdated variables, freeing up memory and improving performance in your scripts.


Clear-Variable [-Force] [-Scope <string>] [-Name <string[]>]


  • -Force: Forces the deletion of variables, even if they are used in other commands.
  • -Scope: Specifies the scope (Local, Global, Script) from which to remove variables. Default: Local.
  • -Name: Specifies the name of the variable(s) to be removed. Accepts wildcard characters (* and ?).


Example 1: Removing a local variable

Clear-Variable -Name localVar

Example 2: Removing all variables in a scope

Clear-Variable -Scope Global

Example 3: Removing multiple variables with a wildcard

Clear-Variable -Name *.temp*

Common Issues

  • Cannot remove a variable that is used in a function: Use the -Force parameter to remove such variables.
  • Cannot remove a read-only variable: Make sure the variable is not set as read-only before trying to delete it.


  • Use Clear-Variable in conjunction with the Get-Variable command to manage variables effectively.
  • Combine Clear-Variable with loops and conditional statements to automate variable cleanup in complex scripts.
  • New-Variable: Creates new variables.
  • Get-Variable: Gets information about variables.
  • Set-Variable: Sets the value of variables.
  • Remove-Variable: Removes variables from a specific scope.