Blog Post

#PowershellBasics: The GetType() and GetTypeCode() methods

,

I’m a DBA. Data types are kind of important to me. I mean I know they are important to developers as well but spend some time as a DBA and they get really important. That makes these two methods of particular interest to me.

GetType()

GetTypeCode()

I’m not 100% certain what all of the types available are but it looks like they are the .NET types with the option to create more.

Examples:

#Create/set variables
$IntVar = 1
$IntArrayVar = 1,2,3
$StringVar = "Test"
$StringArrayVar = "Test","MoreTest"
#GetType() Demo
$IntVar.GetType()
$IntArrayVar[0].GetType()
$IntArrayVar.GetType()
$StringVar.GetType()
$StringArrayVar[0].GetType()
$StringArrayVar.GetType()

You’ll notice that arrays are just listed as array and that I had to pull just a single element to get the actual type. This kind of makes sense since these variables aren’t specifically typed. If you do specifically type them you get better information:

#Create/set variables
[int]$IntVarTyped = 1
[int[]]$IntArrayVarTyped = 1,2,3
[string]$StringVarTyped = "Test"
[string[]]$StringArrayVarTyped = "Test","MoreTest"
#GetType() Demo with typed variables
$IntVarTyped.GetType()
$IntArrayVarTyped.GetType()
$StringVarTyped.GetType()
$StringArrayVarTyped.GetType()

You’ll notice that now we get a basetype of System.Array and a name of Int32[] or String[] depending (The []s tell you its an array.)

GetTypeCode() gives you less information (just the name) but is pretty similar.

#GetTypeCode() Demo
$IntVar.GetTypeCode()
$IntArrayVar.GetTypeCode()
$StringVar.GetTypeCode()
$StringArrayVar.GetTypeCode()

Now wait a minute. I only have 4 variables. How did I get back 7 responses? Well GetTypeCode() seems to return a separate line for each element in the array. So an untyped array with two INTs and a STRING would give back explicit information about what’s in the array. INT, INT, STRING for example. So what happens if we type the variables?

#GetTypeCode() Demo with typed variables
$IntVarTyped.GetTypeCode()
$IntArrayVarTyped.GetTypeCode()
$StringVarTyped.GetTypeCode()
$StringArrayVarTyped.GetTypeCode()

Exactly the same. Well that was good to know, if a bit boring.

Note: It appears that while GetTypeCode() is simpler returns a bit more specific information it isn’t always available. I tried this:

$Procs = Get-Process

And GetType() worked while GetTypeCode wasn’t available. From what I can tell GetType() is part of the system object and GetTypeCode is part of the type object.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating