Clear Variable Content in PowerShell

Rohan Timalsina Apr 12, 2022
  1. Use Clear-Variable Cmdlet to Clear Variable Content in PowerShell
  2. Use Remove-Variable Cmdlet to Remove the Variable in PowerShell
Clear Variable Content in PowerShell

A variable is a storage location for a value. You can store all types of values in PowerShell variables.

You can store the outputs of commands and the elements used in commands and expressions, such as names, paths, settings, and values.

Variables are represented by text strings and begin with the $ sign in PowerShell, such as $data, $a, $var. They are not case-sensitive and can include spaces and special characters.

PowerShell has different types of variables: User-created variables, Automatic variables, and Preference variables.

Sometimes when working with variables in PowerShell, you might need to clear the values of variables. This tutorial will teach you to clear variable content in PowerShell.

Use Clear-Variable Cmdlet to Clear Variable Content in PowerShell

The Clear-Variable cmdlet helps to remove the data stored in a variable. It deletes only the value, not a variable.

Clearing the value will assign the variable’s $null (empty) value. It preserves the data or object type stored in the variable.

The following command creates a variable named $var and assigns the string values.

$var = "Hello World"

This command removes the value from the variable $var.

Clear-Variable -Name var

The var variable still exists after it completes the operation, but the value is null.

$var

Output:

It gives no output, which means there is an empty value in the variable.

To remove multiple variable values, you can specify multiple variable names.

Clear-Variable -Name var1 var2 var3

You can also use its built-in alias clv to delete the value of a variable.

clv -Name var

Use Remove-Variable Cmdlet to Remove the Variable in PowerShell

The Remove-Variable cmdlet deletes a variable and its value in PowerShell. This cmdlet does not delete variables set as constants or owned by the system.

The following command removes the variable $num.

Remove-Variable num

This cmdlet has a built-in alias rv. So, you can also use the rv command to delete the variable.

rv variable_name

We hope this article helped you understand how to clear the contents of the variables PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Variable