PowerShell – Does it possible to delete variables?

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

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 “-Name” parameter to delete the variables.

PS C:\> Remove-Variable var

If the variable is exists, it removes the variable. If it doesn’t exists; 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; it 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?

Leave a Reply

Your email address will not be published.

Scroll to top