CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Does it possible to delete variables?

Yes, it is possible to remove the variables defined in PowerShell.

We have discussed creating a variable in PowerShell in the article “PowerShell – How to create Variables?“. Through this article, we are going to discuss how to remove / un-define the variable.

PowerShell provides a command Remove-Variable to delete the variables defined in the current scope.

The Remove-Variable cmdlet

You need to pass the variable name through the “-Name” parameter to delete the variables.

PS C:\> Remove-Variable var

If the variable exists, it removes the variable. If it doesn’t exist; this command will throw the Error:

PS C:\> Remove-Variable var
Remove-Variable : Cannot find a variable with the name 'var'.
At line:1 char:1
+ Remove-Variable var
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (var:String) [Remove-Variable], ItemNotFoundException
    + FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.RemoveVariableCommand

How to verify whether the variable exists?

You can verify it using Get-Variable cmdlet. This is used to get the value of the variable. If the variable exists; Get-Variable will display the value of the variable; otherwise, it will throw the same above Error.

PS C:\> Get-Variable var

Name                           Value
----                           -----
var                            100

[..] David

PowerShell – Does it possible to delete variables?

One thought on “PowerShell – Does it possible to delete variables?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top