Listing Properties with Values (Part 3)

by May 2, 2018

When you want to inspect individual objects and their properties, piping an object to Out-GridView is of limited use: the grid view window will display a single (very long) line with the properties. Try this and see for yourself:

 
PS> Get-Process -Id $pid | Select-Object -Property * | Out-GridView  
 

We have used the below function before to sort out all properties that have no value. But the function can do more. It supports the -AsHashtable parameter which turns an object into a hash table, and can drastically help you display single objects for inspection:

# Only list output fields with content

function Remove-EmptyProperty  {
    param (
        [Parameter(Mandatory,ValueFromPipeline)]
            $InputObject,
            
            [Switch]
            $AsHashTable
    )


    begin
    {
      $props = @()
  
    }
    
    process {
        if ($props.COunt -eq 0)
        {
          $props = $InputObject | 
            Get-Member -MemberType *Property | 
            Select-Object -ExpandProperty Name | 
            Sort-Object
        }
    
        $notEmpty = $props | Where-Object { 
          !($InputObject.$_ -eq $null -or
             $InputObject.$_ -eq '' -or 
             $InputObject.$_.Count -eq 0) |
          Sort-Object
        
        }
        
        if ($AsHashTable)
        {
          $notEmpty | 
            ForEach-Object { 
                $h = [Ordered]@{}} { 
                    $h.$_ = $InputObject.$_ 
                    } { 
                    $h 
                    }
        }
        else
        {
          $InputObject | 
            Select-Object -Property $notEmpty
        }
    }
} 

When -AsHashtable is specified, Out-GridView will display the object vertically instead of horizontally, and since it also eliminates all empty properties and sorts properties alphabetically, it becomes so much easier to view and inspect objects:

 
PS> Get-Process -Id $pid | Select-Object -Property * | Remove-EmptyProperty -AsHashTable | Out-GridView  
 

Try this with an AD user object, for example:

 
PS> Get-ADUser $env:username -Properties * | Remove-EmptyProperty -AsHashTable | Out-GridView  
 

Twitter This Tip! ReTweet this Tip!