Removing Empty Array Elements (Part 1)

Occasionally you come across lists (arrays) with empty elements. What’s the best way of removing empty elements?

Let’s first focus on a common use case: the code below creates a software inventory by reading the installed software from the registry. The software list is then displayed in a grid view window, and most likely you’ll see elements with empty properties:

$Paths = 'HKCU:SoftwareMicrosoftWindowsCurrentVersionUninstall*',
    'HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall*',
    'HKLM:SOFTWAREWOW6432NodeMicrosoftWindowsCurrentVersionUninstall*',
    'HKCU:SOFTWAREWOW6432NodeMicrosoftWindowsCurrentVersionUninstall*'

$software = Get-ItemProperty -Path $paths -ErrorAction Ignore |
  Select-Object -Property DisplayName, DisplayVersion, UninstallString

$software | Out-GridView 

Let’s eliminate all entries with an empty DisplayName:

# remove elements with empty DisplayName property
$software = $software | Where-Object { [string]::IsNullOrWhiteSpace($_.DisplayName)}

Since empty properties can either be “really” empty ($null) or contain an empty string (‘’), you have to check both. A much easier way is using an implicit conversion to Boolea. However, in this case a value of 0 will also be removed:

# remove elements with empty DisplayName property
$software = $software | Where-Object { $_.DisplayName }

Using the simplified syntax introduced in PowerShell 3, you could even write:

# remove elements with empty DisplayName property
$software = $software | Where-Object DisplayName

And if you’d like to save a couple of milliseconds, use the where method instead:

# remove elements with empty DisplayName property
$software = $software.Where{ $_.DisplayName }

If you are dealing with really large arrays, a foreach loop is way more efficient (about 15x faster):

# remove elements with empty DisplayName property
$software = foreach ($_ in $software){ if($_.DisplayName) { $_ }}

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...