PowerShell offers multiple ways to clear variables. You can use the Clear-Variable cmdlet or assign a $null value to the variable.
Method 1: Using the Clear-Variable to Clear Variable
Clear-Variable -Name variable
Method 2: Using the Clear-Variable to Clear Multiple Variables
Clear-Variable -Name variable1,variable2
Method 3: Using the $null to Clear Variable
$variable = $null
All these methods clear the content of the variable.
The following examples show how to use these methods in practice.
Using the Clear-Variable cmdlet to Clear Variable
To clear a variable in PowerShell, you can use the Clear-Variable
cmdlet. This command deletes the contents stored in a variable.
The following PowerShell script shows how to do it.
$variable1 = "This is demo app" Clear-Variable -Name variable1 Write-Output $variable1
In this example, $variable1
stores the data in it. We have used the Clear-Variable
cmdlet that takes the variable name as input and deletes the data stored in a variable, Write-Output
cmdlet prints an empty line.
Output:
Using the Clear-Variable Cmdlet to Clear Multiple Variables
You can use the Clear-Variable
cmdlet to clear multiple variables at once by providing their names separated by commas.
The following PowerShell script shows how to do it in practice.
$myVariable1 = "Hi" $myVariable2 = "Adam" Clear-Variable -Name myVariable1, myVariable2
In this example, after using the Clear-Variable
cmdlet, it clears both variable’s values, not the variable itself.
You can also use the wildcard with the variables to clear multiple variables at once.
$myVariable1 = "Hi" $myVariable2 = "Adam" Clear-Variable -Name myVar*
In this example, we have clear multiple variables with the help of a wildcards pattern used with the variable name. The Clear-Variable
command clear the variable value that name starts with myVar
Using the $null Value to Clear the Variable
To clear a variable value in PowerShell, you can assign it the value of $null
.
The following PowerShell script shows how to do it.
$myVariable = "Hello, Adam!" $myVariable = $null Write-Output $myVariable
In this example, the $myVariable
stores the data in it. By assigning the $null
value to the $myVariable
, it deletes the data stored in the variable. If we try to print the variable value using the Write-Output cmdlet, it will print an empty line.
Conclusion
I hope the above article on how to clear variables in PowerShell using the Clear-Variable
cmdlet and $null are helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.