Removing Null Values

How many times have you gotten a WMI-Object and had to scroll through screens of null values? Here's a quick way to generate a new PSCustomObject that has those values removed. Note that this is NOT the same object type as the input object, and it does not have any of the methods the original object has. It only has the properties. However the returned object's .__Base property contains the full object.

function Remove-NullValue {
    param(
        [Parameter(
            Position = 0,
            Mandatory = $true,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName =$true
        )]
        [Alias('Object')]
        [Object[]]$inputObject
    );

    process {
        foreach ($object in $inputObject) {
            $outputObject = New-Object -TypeName PsObject;
            Add-Member -InputObject $outputObject -MemberType ScriptMethod -name AddNoteProperty -value {
                Add-Member -InputObject $this -MemberType NoteProperty -name $args[0] -value $args[1]
            };
            Get-Member -MemberType *Propert* -InputObject $object | % {
                $name = $_.name;
                if ($object.$name) {
                    $outputObject.AddNoteProperty($name, $object.$name);
                }
            }
$outputObject.AddNoteProperty('__Base', $object);
            $outputObject;
        }
    }
}

New-Alias -Name rnv -Value Remove-NullValue;

 

Remember, this returns a PSCustomObject, not the original object.