PowerShell – How to reset Variables (using Clear-Variable)?

We have discussed setting the values to the variables in PowerShell, in our previous article. Through this article, we will discuss resetting the values; means, clear the content of the variables.

PowerShell provides a command to reset the variables. This is very helpful; especially when we have to manage a long script where it is needed to deal with multiple variables.

The Clear-Variable cmdlet

This command is used to clear the content of a single variable or multiple variables. Variables? Yes. This command has the capability to clear the content of multiple variables. Keep that in mind, this command will not delete or remove the variable(s); it just clears the content of the variable(s).

You need to pass the variable whose content has to be cleared through its “-Name” parameter. If the provided variable name doesn’t exist; it doesn’t do anything. That means, it WILL NOT create a variable with a null value; if the variable doesn’t exist.

Clearing the variable means, assign the null value to the variable. a null value means, it is nothing; not even an empty string or a 0 value.

Here is an example, to clear the content of a single variable $var.

PS C:\> Clear-Variable -Name "var"

As it supports deleting the content of multiple variables; you can pass the list of variables separated by a comma and enclosed in the parentheses. Here is an example to delete the content of multiple variables;

PS C:\> Clear-Variable -Name ("var1", "var2", "var3")

Using wildcards

This command allows wildcard characters also. That means you can specify the multiple variables using wild cards. For example, the above command can be written using wildcards as below;

PS C:\> Clear-Variable var*

This clears the content of all the variables, which are starting with “var”. You have to be careful when you use wildcards; because it clears all the variables to satisfy the wildcard; even though those variables are created through other scripts.

[..] David

PowerShell – How to reset Variables (using Clear-Variable)?

Leave a Reply

Your email address will not be published.

Scroll to top