Skip to main content

Diving in deep with GetType()

When I deliver PowerShell classes, I emphasis the importance of sending the objects in the PowerShell Pipeline to Get-Member so you know what information is contained inside the object.  I also do it to get the typename of the object so I can do further research on MSDN.  Recently I’ve started using the .GetType() method if I only need the type information.  Get a look at the difference.

PS C:\> Get-Date | GM


   TypeName: System.DateTime

Name                 MemberType     Definition                                
----                 ----------     ----------                                
Add                  Method         datetime Add(timespan value)              
AddDays              Method         datetime AddDays(double value)            
AddHours             Method         datetime AddHours(double value)           
AddMilliseconds      Method         datetime AddMilliseconds(double value)    
AddMinutes           Method         datetime AddMinutes(double value)         
AddMonths            Method         datetime AddMonths(int months)            

… 60 members removed for this output …

TimeOfDay            Property       timespan TimeOfDay {get;}                 
Year                 Property       int Year {get;}                           
DateTime             ScriptProperty System.Object DateTime {get=if ((& { Set...


Or
PS C:\> (Get-Date).GetType()

IsPublic IsSerial Name                                     BaseType            
-------- -------- ----                                     --------           
True     True     DateTime                                 System.ValueType   


A little bit easier to get SYSTEM.DATETIME from the second example.  One member of my PowerShell Toolmaking class asked me what does IsSerial mean?  Good question.  This one took a little bit of research.  I first had to figure out the object type that was giving me this information.

PS C:\> Get-Member -InputObject (Get-Date).GetType()


   TypeName: System.RuntimeType

Name                           MemberType Definition                          
----                           ---------- ----------                          
Equals                         Method     bool Equals(System.Object o), bool...
FindInterfaces                 Method     type[] FindInterfaces(System.Refle...
FindMembers                    Method     System.Reflection.MemberInfo[] Fin...
GetArrayRank                   Method     int GetArrayRank(), int _Type.GetA...
GetConstructor                 Method     System.Reflection.ConstructorInfo ...
GetConstructors                Method     System.Reflection.ConstructorInfo[...
GetCustomAttributes            Method     System.Object[] GetCustomAttribute...
GetCustomAttributesData        Method     System.Collections.Generic.IList[S...
GetDefaultMembers              Method     System.Reflection.MemberInfo[] Get...
GetElementType                 Method     type GetElementType(), type _Type....
GetEnumName                    Method     string GetEnumName(System.Object v...
GetEnumNames                   Method     string[] GetEnumNames()             
GetEnumUnderlyingType          Method     type GetEnumUnderlyingType()        
GetEnumValues                  Method     array GetEnumValues()               
GetEvent                       Method     System.Reflection.EventInfo GetEve...
GetEvents                      Method     System.Reflection.EventInfo[] GetE...
GetField                       Method     System.Reflection.FieldInfo GetFie...
GetFields                      Method     System.Reflection.FieldInfo[] GetF...
GetGenericArguments            Method     type[] GetGenericArguments()        
GetGenericParameterConstraints Method     type[] GetGenericParameterConstrai...
GetGenericTypeDefinition       Method     type GetGenericTypeDefinition()     
GetHashCode                    Method     int GetHashCode(), int _MemberInfo...
GetIDsOfNames                  Method     void _MemberInfo.GetIDsOfNames([re...
GetInterface                   Method     type GetInterface(string name), ty...
GetInterfaceMap                Method     System.Reflection.InterfaceMapping...
GetInterfaces                  Method     type[] GetInterfaces(), type[] _Ty...
GetMember                      Method     System.Reflection.MemberInfo[] Get...
GetMembers                     Method     System.Reflection.MemberInfo[] Get...
GetMethod                      Method     System.Reflection.MethodInfo GetMe...
GetMethods                     Method     System.Reflection.MethodInfo[] Get...
GetNestedType                  Method     type GetNestedType(string name), t...
GetNestedTypes                 Method     type[] GetNestedTypes(), type[] Ge...
GetProperties                  Method     System.Reflection.PropertyInfo[] G...
GetProperty                    Method     System.Reflection.PropertyInfo Get...
GetType                        Method     type GetType(), type _MemberInfo.G...
GetTypeInfo                    Method     void _MemberInfo.GetTypeInfo(uint3...
GetTypeInfoCount               Method     void _MemberInfo.GetTypeInfoCount(...
Invoke                         Method     void _MemberInfo.Invoke(uint32 dis...
InvokeMember                   Method     System.Object InvokeMember(string ...
IsAssignableFrom               Method     bool IsAssignableFrom(type c), boo...
IsDefined                      Method     bool IsDefined(type attributeType,...
IsEnumDefined                  Method     bool IsEnumDefined(System.Object v...
IsEquivalentTo                 Method     bool IsEquivalentTo(type other)     
IsInstanceOfType               Method     bool IsInstanceOfType(System.Objec...
IsSubclassOf                   Method     bool IsSubclassOf(type c), bool _T...
MakeArrayType                  Method     type MakeArrayType(), type MakeArr...
MakeByRefType                  Method     type MakeByRefType()                
MakeGenericType                Method     type MakeGenericType(Params type[]...
MakePointerType                Method     type MakePointerType()              
ToString                       Method     string ToString(), string _MemberI...
Assembly                       Property   System.Reflection.Assembly Assembl...
AssemblyQualifiedName          Property   string AssemblyQualifiedName {get;} 
Attributes                     Property   System.Reflection.TypeAttributes A...
BaseType                       Property   type BaseType {get;}                
ContainsGenericParameters      Property   bool ContainsGenericParameters {get;}
CustomAttributes               Property   System.Collections.Generic.IEnumer...
DeclaringMethod                Property   System.Reflection.MethodBase Decla...
DeclaringType                  Property   type DeclaringType {get;}           
FullName                       Property   string FullName {get;}              
GenericParameterAttributes     Property   System.Reflection.GenericParameter...
GenericParameterPosition       Property   int GenericParameterPosition {get;} 
GenericTypeArguments           Property   type[] GenericTypeArguments {get;}  
GUID                           Property   guid GUID {get;}                    
HasElementType                 Property   bool HasElementType {get;}          
IsAbstract                     Property   bool IsAbstract {get;}              
IsAnsiClass                    Property   bool IsAnsiClass {get;}             
IsArray                        Property   bool IsArray {get;}                 
IsAutoClass                    Property   bool IsAutoClass {get;}             
IsAutoLayout                   Property   bool IsAutoLayout {get;}            
IsByRef                        Property   bool IsByRef {get;}                 
IsClass                        Property   bool IsClass {get;}                 
IsCOMObject                    Property   bool IsCOMObject {get;}             
IsConstructedGenericType       Property   bool IsConstructedGenericType {get;}
IsContextful                   Property   bool IsContextful {get;}            
IsEnum                         Property   bool IsEnum {get;}                   
IsExplicitLayout               Property   bool IsExplicitLayout {get;}        
IsGenericParameter             Property   bool IsGenericParameter {get;}      
IsGenericType                  Property   bool IsGenericType {get;}           
IsGenericTypeDefinition        Property   bool IsGenericTypeDefinition {get;} 
IsImport                       Property   bool IsImport {get;}                
IsInterface                    Property   bool IsInterface {get;}             
IsLayoutSequential             Property   bool IsLayoutSequential {get;}      
IsMarshalByRef                 Property   bool IsMarshalByRef {get;}          
IsNested                       Property   bool IsNested {get;}                
IsNestedAssembly               Property   bool IsNestedAssembly {get;}        
IsNestedFamANDAssem            Property   bool IsNestedFamANDAssem {get;}     
IsNestedFamily                 Property   bool IsNestedFamily {get;}          
IsNestedFamORAssem             Property   bool IsNestedFamORAssem {get;}      
IsNestedPrivate                Property   bool IsNestedPrivate {get;}         
IsNestedPublic                 Property   bool IsNestedPublic {get;}          
IsNotPublic                    Property   bool IsNotPublic {get;}             
IsPointer                      Property   bool IsPointer {get;}               
IsPrimitive                    Property   bool IsPrimitive {get;}             
IsPublic                       Property   bool IsPublic {get;}                
IsSealed                       Property   bool IsSealed {get;}                
IsSecurityCritical             Property   bool IsSecurityCritical {get;}      
IsSecuritySafeCritical         Property   bool IsSecuritySafeCritical {get;}  
IsSecurityTransparent          Property   bool IsSecurityTransparent {get;}   
IsSerializable                 Property   bool IsSerializable {get;}          
IsSpecialName                  Property   bool IsSpecialName {get;}           
IsUnicodeClass                 Property   bool IsUnicodeClass {get;}          
IsValueType                    Property   bool IsValueType {get;}             
IsVisible                      Property   bool IsVisible {get;}               
MemberType                     Property   System.Reflection.MemberTypes Memb...
MetadataToken                  Property   int MetadataToken {get;}            
Module                         Property   System.Reflection.Module Module {g...
Name                           Property   string Name {get;}                  
Namespace                      Property   string Namespace {get;}             
ReflectedType                  Property   type ReflectedType {get;}           
StructLayoutAttribute          Property   System.Runtime.InteropServices.Str...
TypeHandle                     Property   System.RuntimeTypeHandle TypeHandl...
TypeInitializer                Property   System.Reflection.ConstructorInfo ...
UnderlyingSystemType           Property   type UnderlyingSystemType {get;}    


Wow! A lot of information here.  The first that I was able to get was the typename.  It took some browsing around, but I found the object information on MSDN.  https://msdn.microsoft.com/en-us/library/system.type.aspx
The problem that I have now is that IsSerial is not listed in the member information.  I can see IsSerializable is there, but I need to confirm that the column named IsSerial represents IsSerializable.  Here is a little code that will comb all of PowerShell’s formatting files and tell you where to find the correct XML file to investigate.

$Files = Get-ChildItem -Recurse -Path "C:" -Name "*.format.ps1xml"

ForEach ($F in $Files)
{
  ForEach ($Data in (Get-Content -Path "C:\$F"))
  {
   
    If ($Data -like "*System.RuntimeType*")
    {Write-Host "Found: $F" -ForegroundColor Green}
  } 
}


When I run this code, I find 2 potential candidates:
Found: Windows\System32\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml
Found: Windows\System32\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml
Found: Windows\SysWOW64\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml
Found: Windows\SysWOW64\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml
Found: Windows\WinSxS\amd64_microsoft.windows.powershell.common_31bf3856ad364e35_10.0.10586.0_none_bd64e8
b0c5905011\PowerShellCore.format.ps1xml
Found: Windows\WinSxS\amd64_microsoft.windows.powershell.common_31bf3856ad364e35_10.0.10586.0_none_bd64e8
b0c5905011\PowerShellCore.format.ps1xml
Found: Windows\WinSxS\wow64_microsoft.windows.powershell.common_31bf3856ad364e35_10.0.10586.0_none_c7b993
02f9f1120c\PowerShellCore.format.ps1xml
Found: Windows\WinSxS\wow64_microsoft.windows.powershell.common_31bf3856ad364e35_10.0.10586.0_none_c7b993
02f9f1120c\PowerShellCore.format.ps1xml

After evaluating the formatting file, I was able to confirm the IsSerial represents IsSerializable.
               
                   
                       
                        8
                   
                    
                       
                        8
                   
                   
                        40
                   
                   
               
               
                   
                       
                           
                                IsPublic
                           
                           
                                IsSerializable
                           
                           
                                Name
                           
                           
                                BaseType
                           
                       
                   
               
           


So, what does this property mean?  In basic terms, it allows the contents of this object to be saved to disk.  Yes, a lot of research needed to be done. To make sure that you understand what you are looking at, you need to do your research.

Welcome to Computer Science.


Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.