How to Use GetType() in PowerShell


You can use the GetType() command in PowerShell to retrieve information about how a particular variable is stored.

Here are several common ways to use this command in practice:

Method 1: Use GetType() to Retrieve Variable Information

$my_var.GetType()

Method 2: Use GetType() to Retrieve Variable Type Only

$my_var.GetType().Name

Method 3: Use GetType() to Check if Variable is Specific Type

$my_var.GetType().Name -eq 'String'

The following examples show how to use each method in practice.

Example 1: Use GetType() to Retrieve Variable Information

We can use the following syntax to create a variable named $my_var that contains the value 100 and then use the GetType() command to retrieve information about the variable:

$my_var = 100
$my_var.GetType()

The following screenshot shows how to use this syntax in practice:

This returns the following information about the $my_var variable:

  • IsPublic: Whether the variable is public (True)
  • IsSerial: Whether the variable is serializable (True)
  • Name: The variable type (Int32)

Example 2: Use GetType() to Retrieve Variable Information

We can use the following syntax to create a variable named $my_var that contains the value 100 and then use the GetType().Name command to only retrieve the variable type:

$my_var = 100
$my_var.GetType().Name

The following screenshot shows how to use this syntax in practice:

PowerShell GetType() command to get variable type

Notice that this returns only the value Int32, which tells us that the $my_var variable is an integer.

Example 3: Use GetType() to Check if Variable is Specific Type

We can use the following syntax to create a variable named $my_var that contains the value 100 and then use the GetType().Name command along with the -eq operator to check if the variable is a specific type:

$my_var = 100
$my_var.GetType().Name -eq 'String'

The following screenshot shows how to use this syntax in practice:

PowerShell check if variable is equal to specific type

This returns False, which tells us that the variable named $my_var is not a string.

Feel free to replace String with any other variable type you’d like to check if a given variable is equal to a specific type.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Convert String to Double
PowerShell: How to Convert String to Datetime
PowerShell: How to Create a Boolean Variable

Leave a Reply