Working with Types

You can do a lot with PowerShell and not have to worry about the type of data stored in a variable. However in my experience as soon as you start working with data from external sources you end of having to think about it. I have been working with a JSON file, which is an export from MongoDB (see MongoDB - Wikipedia, the free encyclopedia), the issue here is that MongoDB stores documents not well structured tables so the datatype can vary and some "fields" will be missing. So here are some things I learnt.

PowerShell Types

So I guess the first thing to note is that yes, everything in PowerShell does indeed have a type, here are some examples:

  • System.String
  • System.Int32
  • System.Boolean
  • System.Object[] - an array of objects

Checking Type

Sometimes it is not obvious what type some variable is, this is especially true when you are looping over data, typically you'll get an exception but this is when I start logging the type to try and see what is going on. The best way to do this is with $MyVar.GetType().FullName which gives you the fully qualified name of the type, however $MyVar.GetType().Name also works and gives you the shortened name. Just to be clear $MyVar.GetType() is actually a type, System.RuntimeType which has its own properties and methods.

Specifying Type

You can easily specify the type of a variable, if you wish, this way you know what should happen and that errors are poor data. So to declare a string, you can do this [string]$MyVar = "" or [System.string]$MyVar = "", which is the exact same type. If we then do $MyVar = 15 then PowerShell will convert the number to a string and store the string representation in $MyVar.

Changing or Casting

Of course now we have started wandering into type conversion, a simple conversion is this $MyVar = [string]15, which is not necessary as PowerShell will do this for you. Of course some conversions will result in an error, like [Int32]$MyVar = "23a"

Handy Operators

There are two operators that are very handy when working with types, first up "-is" which is a great way to test first!
if ($MyVar -is [Int32]) {
  Write-Host "MyVar is an integer"
} else {
  Write-Host "MyVar is not an integer"
}

The next one is "-as" which is a cautious conversion, returning the converted value if possible but otherwise returning $null, so it prevents runtime exceptions.
if (($MyVar -as [Int32]) -ne $null) {
  Write-Host "MyVar is an integer"
} else {
  Write-Host "MyVar is not an integer"
}

Although you probably want to use this better than my example.