Functions/Remove-EmptyProperty.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function Remove-EmptyProperty  {
<#
.SYNOPSIS
    To take an object and return only non-empty properties
.DESCRIPTION
    To take an object and return only non-empty properties
.PARAMETER InputObject
    The object that you want empty properties to be removed. Value from pipeline.
.PARAMETER AsHashTable
    To return a hashtable as opposed to another object
.EXAMPLE
    $A = New-Object -TypeName 'psobject' -Property ([Ordered] @{
    Name = 'test'
    EmptyProperty = $null
    })
    $A
 
    Name EmptyProperty
    ---- -------------
    test
 
    Remove-EmptyProperty -InputObject $A
 
    Name
    ----
    test
.EXAMPLE
    Remove-EmptyProperty -InputObject $A -AsHashTable
 
    Name Value
    ---- -----
    Name test
.NOTES
    # from: http://community.idera.com/powershell/powertips/b/tips/posts/listing-properties-with-values-part-3
#>


    [CmdletBinding(ConfirmImpact='Low')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments','')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')]
    param (
        [Parameter(Mandatory,Position=0,ValueFromPipeline)]
            $InputObject,

            [Switch]
            $AsHashTable
    )

    begin {
        Write-Verbose -Message "Starting [$($MyInvocation.Mycommand)]"
        $props = @()
    }

    process {
        if ($props.Count -eq 0) {
            $props = $InputObject |
                Get-Member -MemberType *Property |
                Select-Object -ExpandProperty Name |
                Sort-Object
        }

        $notEmpty = $props | Where-Object {
            -not (($null -eq $InputObject.$_ ) -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
        }
    }

    end {
        Write-Verbose -Message "Ending [$($MyInvocation.Mycommand)]"
    }
}