Using PowerShell's Get-Member Cmdlet to Interrogate Objects

The Get-Member cmdlet is arguably the most useful cmdlet in PowerShell and often goes unnoticed by new PowerShell users. You can think of Get-Member as your detective's magnifying glass. The cmdlet allows you to learn about an object's properties and methods that you can call.

When you use Get-Member on a collection it will return the properties and methods about each Type within the collection. Below are the most commonly used switches on the cmdlet to take note of:

-Static: Return only static methods and properties.
-Name: Return only properties that match the provided name which can contain wild cards.
-MemberType: Commonly used with the value "Property" or "Method" to return only those members.

The following example shows how to get the members of a system event log message:

                                        
 #
 # Grab the first error record
 #   in the system event log.
 #
 $event = Get-EventLog -LogName System -EntryType error | select -First 1

 #
 # List all Members of the "EventLogEntry" object
 #
 $event | Get-Member

 #
 # List only Properties
 #
 $event | Get-Member -MemberType Property

 #
 # List only Methods
 #
 $event | Get-Member -MemberType Method

                                        

If you run these commands you will see how the "-MemberType" will filter the results. At the top of the results you will see a message like: "TypeName: System.Diagnostics.EventLogEntry". This is the "Type" of object for which members are being listed. Sometimes it's good to know the full type name of the object in case you want to research more about it.

You may have also noticed that in the results there is a "Definition" column which shows the datatype of the properties as well as method overloads.Often these will be common types like "String" or "DateTime", but if you see something unfamiliar you can always do another Get-Member on any of the properties to get more details about it.

Now that we know what properties are available we can use them to extract information from the event log:

                                        
 #
 # Write Details about the log
 #
 Write-Host "Message: $($event.Message)"
 Write-Host "Time: $($event.TimeGenerated)"
 Write-Host "Type: $($event.EntryType)"
 
 Message: The device, \Device\Ide\iaStor0, did not respond within the timeout period.
 Time: 10/11/2013 21:34:20
 Type: Error


                                        

In summary, Get-Member along with Get-Help are your best tools for inquiring about objects in PowerShell.

Bonus Tip:

  The Get-Member cmdlet has an alias "gm" which you can use to save on typing.

                                        


© 2024 Embrs.net