So I got a question about a variable that was acting up in a colleague’s script, so we took a look together and solved it. I really like what he managed to do once we figured it out. Lars made a script that configured some parts of IIS site from a CSV file (blog post in swedish, script in english). At one time we had a variable called $test and that was casted to string. Then later we were trying to use the same variable for a hashtable and it didn’t work.

What happens if you cast a variable and then try to enter some other type into it.

PS C:\> #First we cast the variable as a string.
PS C:\> [string]$test = 'Important string'
PS C:\> #Used test
PS C:\> #Reused $test but as a Hashtable
PS C:\> $test = @{Hash='Table'}
PS C:\> $test
System.Collections.Hashtable
PS C:\> $test.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

PS C:\> $test = $Null
PS C:\> $test

PS C:\> $test.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

PS C:\> #So even assigning null does not break the casting
PS C:\> Remove-Variable test
PS C:\> $test.gettype()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $test.gettype()
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PS C:\> #There and now we can use it without requirement of casting.

So remember to remove the variable using Remove-Variable when you are done.

Or you could just recast it everytime..

PS C:\> #Of course you can cast each time
PS C:\> [string]$test = 'Important string'
PS C:\> [hashtable]$test = @{Hash='Table'}
PS C:\> $test.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object