Turning Objects into Hash Tables

by Oct 31, 2019

Often, a single object needs to be examined, i.e. a process or an Active Directory user. When you display an object in a grid view window such as Out-GridView, the entire object is displayed in one long line.

A much better approach is to convert an object into a hash table. This way, each property is displayed in its own line, and you can search for individual properties via the text filter on top of the grid view window. In addition, you have full control over the conversion, so you can sort the object properties and make sure they are in alphabetical order, and even exclude empty properties.

Here is a function that turns objects into hash tables and excludes empty properties on request:

function Convert-ObjectToHashtable
{
    param
    (
        [Parameter(Mandatory,ValueFromPipeline)]
        $object,

        [Switch]
        $ExcludeEmpty
    )

    process
    {
        $object.PSObject.Properties | 
        # sort property names
        Sort-Object -Property Name |
        # exclude empty properties if requested
        Where-Object { $ExcludeEmpty.IsPresent -eq $false -or $_.Value -ne $null } |
        ForEach-Object { 
            $hashtable = [Ordered]@{}} { 
            $hashtable[$_.Name] = $_.Value 
            } { 
            $hashtable 
            } 
    }
}

Let’s take a look at how a single object, i.e. the current process, displays in Out-GridView by default:

$process = Get-Process -Id $pid | Out-GridView 

Compare this:

$process = Get-Process -Id $pid | Convert-ObjectToHashtable -ExcludeEmpty | Out-GridView

So much better to analyze now.


Twitter This Tip! ReTweet this Tip!