Search code examples
powershellpowershell-5.0

Remove-Variable - Cannot find a variable with the name


I have a powershell script that with the following hashtable

[HashTable]$folder_and_prefix = @{}

After a certain point in my script I no longer need that hashtable, I tried doing:

Remove-Variable $folder_and_prefix

but I get the following error:

Remove-Variable : Cannot find a variable with the name 'System.Collections.Hashtable'

Is it possible to remove a hastable that I no longer need?


Solution

  • This is a common mistake. Remove-Variable is taking the name of the variable (a [String]), and by referencing the variable itself (with a dollar sign $) you are passing the value. Remove the dollar sign and that's all you need:

    Remove-Variable folder_and_prefix
    

    Further, it takes an array of names, so you can do:

    $var1 = 5
    $var2 = 'Hello'
    $var3 = @{}
    
    Remove-Variable var1,var2,var3
    

    And it accepts wildcards:

    Remove-Variable var*
    

    The wildcard acceptance is also true for Set-Variable, Get-Variable, and Clear-Variable (New-Variable is the exception).