Removing Empty Object Properties (All Versions)

by Nov 29, 2012

In a previous tip we showed how you can remove all empty properties from an object and also sort its properties alphabetically. The code required PowerShell 3.0 features.

Here is a variation that runs on all PowerShell versions. Again, it takes a BIOS object from WMI and removes empty properties plus sorts the object properties:

$bios = Get-WmiObject -Class Win32_BIOS
$biosNew = $bios |
Get-Member -MemberType *Property |
Select-Object -ExpandProperty Name |
Sort-Object |
ForEach-Object -Begin { $obj=New-Object PSObject } {
  if ($bios.$_ -eq $null)
  {
    Write-Warning "Removing empty property $_"
  }
  else
  {
    $obj | Add-Member -memberType NoteProperty -Name $_ -Value $bios.$_
  }
}{$obj}

$biosNew
 

Twitter This Tip! ReTweet this Tip!