Skip to the main content.

PowerShell Tips

Filter empty PowerShell properties

Table of contents

Post Featured Image

Tobias & Aleksandar's tip #10:

The two very well-known PowerShell experts have teamed up to share their best and most helpful PowerShell tips.

We will be publishing their scripts over the course of Scriptember in 13 blog posts. Don't miss their insights! Be sure to follow all Scriptember events, listed in our calendar here

 

Overview of all 13 articles published during Scriptember

 

 

Filter empty properties

Occasionally, you receive objects with a lot of empty properties that you are not really interested in. You could use Select‑Object to manually select properties, but if the empty properties change, an automated solution would be helpful.

Fortunately, PowerShell adds a secret PSObject extension to each object that reveals the entire object structure, including properties and their values. This way, a simple filter function would look like this:


filter Filter-EmptyProperty
{
   $hashtable = [Ordered]@{}
   foreach ($property in $_.PSObject.Properties)
   {
      if ($property.Value)
      {
         $hashtable[$property.Name]=$property.Value
      }
   }
   [PSCustomObject]$hashtable


In essence, for each object, all of its properties are checked for a value, and only if a value is found, then the property is added to an ordered hash table. Once all desired properties have been collected, the ordered hash table is turned to an object and emitted.

Try these commands (or any other source command that returns empty properties):


# includes empty properties
Get-ComputerInfo -Property *

# shows only populated properties
Get-ComputerInfo -Property * | Filter-EmptyProperty 

 

 

Good2know


Scriptember! Stay tuned:

During Scriptember, our calendar provides the best possible overview.  

Scriptember - hier ist die Übersicht

 

  • Follow us on social media, look for and use the hashtags #Scriptember and #PowerShell.
  • Join our live sessions, overview soon here.
  • Participate in challenges and contests. 
  • Share your knowledge.

 

Find all events here!

 

 

Related links 



Related posts

7 min read

Hidden configuration variables in PowerShell

Tobias & Aleksandar's tip #13:

The two very well-known PowerShell experts have teamed up to share their best and most...

4 min read

Hiding confirmations in PowerShell

Tobias & Aleksandar's tip #12:

The two PowerShell experts have teamed up to share their best and most helpful...

4 min read

URL Encoding in PowerShell

Tobias & Aleksandar's tip #11:

The two very well-known PowerShell experts have teamed up to share their best and most...

About the author: