Home » PowerShell Tips » GetType – Get Variable Data Type in PowerShell

GetType – Get Variable Data Type in PowerShell

PowerShell has different data types like integers, DateTime, float, strings, booleans, etc… Variables in PowerShell store any type of object. GetType method is used to get the data type of variable.

PowerShell GetType method returns the current data type of variable.GetType method returns the name and base type property for a variable.

It’s always best practice to check the data type of variables before doing addition, concatenation, division, or any kind of operation using multiple variables.

In this article, I will explain how to use PowerShell GetType() to get the data type of variable.

PowerShell GetType Examples

PowerShell GetType method gets the current data type of a variable. Let’s understand getType() method with an examples.

Let’s consider an example to assign a company name in a variable as given below

 $CompanyName = "ShellGeek" 
 $CompanyName.GetType()  

$CompanyName variable in PowerShell holds ShellGeek value.

To get variable type, use GetType( ) method.

It returns IsPublic, IsSerial, Name, and BaseType properties. $CompanyName variable is of String data type.

The output of above to get variable data type as below

PowerShell GetType() method
PowerShell GetType() method

GetType – Get Variable Type

Let’s take other examples to get variable type as given below

Get Variable Type for numeric data

 $phone = 12345679     
 $phone.GetType().Name 

In the above example, the $phone variable contains number data assigned to it. Using the GetType() method and its Name property, we can get a variable type as Int32

Cool Tip: How to use get variable in PowerShell!

Check Variable Type for date

$curDate = Get-Date 
$curDate 
$curDate.GetType()

In the above example, the $curDate variable holds the Get-Date value.

Using the GetType method over variable returns the DateTime variable type.

Get Variable Type for array

$Test = '1','2','3','4','5' 
$Test.GetType()

In the above PowerShell script example, the $Test variable contains numeric data separated by, (comma).

To get data type of variable $Test, use GetType(). It will return the data type as Object[] which is the base type of Array.$Test variable that contains an array.

Cool Tip: How to use test-connection to ping a list of computers!

Conclusion

I hope the above article to get variable type using PowerShell GetType() method is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.