How to exclude non-valued object properties when converting to JSON in Powershell

后端 未结 4 1877
独厮守ぢ
独厮守ぢ 2020-12-31 10:40

I have a piece of code that works but I want to know if there is a better way to do it. I could not find anything related so far. Here are the facts:

  • I have an
4条回答
  •  有刺的猬
    2020-12-31 11:02

    I have the following function in my profile for this purpose. Advantage: I can pipe a collection of objects to it and remove nulls from all the objects on the pipeline.

    Function Remove-Null {
        [cmdletbinding()]
        param(
            # Object to remove null values from
            [parameter(ValueFromPipeline,Mandatory)]
            [object[]]$InputObject,
            #By default, remove empty strings (""), specify -LeaveEmptyStrings to leave them.
            [switch]$LeaveEmptyStrings
        )
        process {
            foreach ($obj in $InputObject) {
                $AllProperties = $obj.psobject.properties.Name
                $NonNulls = $AllProperties |
                    where-object {$null -ne $obj.$PSItem} |
                    where-object {$LeaveEmptyStrings.IsPresent -or -not [string]::IsNullOrEmpty($obj.$PSItem)}
                $obj | Select-Object -Property $NonNulls
            }
        }
    }
    

    Some examples of usage:

    $AnObject = [pscustomobject]@{
        prop1="data"
        prop2="moredata"
        prop5=3
        propblnk=""
        propnll=$null
    }
    $AnObject | Remove-Null
    
    prop1 prop2    prop5
    ----- -----    -----
    data  moredata     3
    
    $ObjList =@(
        [PSCustomObject]@{
            notnull = "data"
            more = "sure!"
            done = $null
            another = ""
        },
        [PSCustomObject]@{
            notnull = "data"
            more = $null
            done = $false
            another = $true
        }
    )
    $objList | Remove-Null | fl #format-list because the default table is misleading
    
    notnull : data
    more    : sure!
    
    notnull : data
    done    : False
    another : True
    

提交回复
热议问题