Get Object Type in PowerShell

Get Object type in PowerShell

Using GetType() Method

Use the GetType() method to get the object’s data type in PowerShell.

We used the GetType() method to get the data type of an object we saved in the $string variable. The returned object will be an instance of the System.Type class, which contains information about the type, such as its Name, BaseType and other properties (you can see in the above output), the Name denotes the data type of the object stored in $string.

It is important to note that if the $string variable is not defined or not initialized with any value, it will throw an error stating, You cannot call a method on a null-valued expression. We can also use this command to check the type of any other variable or object like (5).GetType() will return the following results:

If you are only interested in getting the Name of the data type, then we can use the Name property chained with GetType() as follows:

Use the FullName property to get the complete name of an object’s data type.

If you are looking for a solution that provides you with the data type of the specified object and serves you with the properties and methods, then the following solution is for you.

Using Get-Member Cmdlet

Use the GetMember cmdlet to get the object’s data type in PowerShell.

Here, we used the Get-Member cmdlet with the -InputObject parameter to retrieve the properties and methods of an object stored in a variable $string.

The Get-Member cmdlet is used to display the properties and methods of an object. The -InputObject parameter was used to specify the object for which the properties and methods are to be displayed. By default, it only shows the members the object has at runtime; if you want to see all the members, you can use the -Force parameter.

The command Get-Member -InputObject $string will display the properties and methods of the object stored in the variable $string. This will include properties such as Length and Chars and methods such as CompareTo, Contains, EndsWith, IndexOf, Insert, LastIndexOf, Remove, Replace, Split, StartsWith, Substring, ToLower, ToUpper, Trim, TrimEnd, TrimStart, PadLeft, PadRight, Join, Format, Concat, Clone and many more.

You can use Get-Member on any other variable or object, which will list the properties and methods available for that object. For example, let’s use it with the date-type data below.

NOTE: We used three dots (... ) in the last two output blocks to show continuity, as we can’t write all properties and methods here.

That’s all about how to get Object type in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *