Powershell

How to Use GetType to Check Variable Type in PowerShell

PowerShell includes several data types, including integers, strings, boolean, integers, or floats. These data types are then stored in the variables. PowerShell can detect the data type on its own. But it is a best practice to check the variable’s data type before executing any operations on that variable. More specifically, PowerShell uses the “GetType()” method to check the data type of any given variable.

This post will overview the “GetType()” function in PowerShell.

What is the GetType() Method in PowerShell?

The “GetType()” method checks the data type of the given variable. Using this method, you can find out what type of data is contained in the given variable, along with its name and base type property.

Syntax

GetType().Name

In the above-given syntax, we will fetch the value of the “Name” property using the “GetType()” method.

How to Use GetType to Check Variable Type in PowerShell?

In this section, we have compiled some examples to check the variable type using the GetType() method in PowerShell.

Example 1: Check the Data Type of an Integer Variable

This example will examine the integer value’s data type:

$a = 1

$a.GetType().Name

In the above code example:

  • First, we have assigned an integer value to a variable “$a”.
  • After that, we concatenate the variable with the “GetType()” method:

The output confirms that the given variable is of integer “Int32” type.

Example 2: Check the Data Type of a String Variable

Now, let’s store a string value and perform the same operation:

$a = "abc"

$a.GetType().Name

The output displayed “String” as the data type of the accessed variable.

Conclusion

The “GetType()” method is used to examine the data type of the variable. To check the data type of any data type, first, the value must be stored in a variable. After that, use the “GetType()” method to get the data type along with its name and the base type. This blog has presented a detailed guide about the GetType() method.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.