locked
Add a Property to a PSObject only if it has a value (exists) RRS feed

  • Question

  • Hello Guys,

    I need some advises on how to add a property to an existing PSObject, but only if the property has a value. For example:

    $OutObj = New-Object -TypeName PSObject
    Add-Member -InputObject $OutObj -Type noteproperty -Name Id -Value $Id
    Add-Member -InputObject $OutObj -Type noteproperty -Name Name -Value $Name
    Add-Member -InputObject $OutObj -Type noteproperty -Name Group -Value $group


    What I would like to achieve is adding the property only if it has a value. So far I did a check of every single property and if it exists I add it to the object...something like:

    if ($Id) {
    Add-Member -InputObject $OutObj -Type noteproperty -Name Id -Value $Id
    }

    but I find this a bit uncool when the number of properties rises. 

    Any ideas how to optimize this?

    Thanks!


    Monday, February 18, 2019 3:55 PM

Answers

  • Or do it using PwoerSHell.

    $props = @{}
    if($Name){$props.Add('Name',$name)}
    if($group){$props.Add('Group', $group)}
    $obj = [pscustomobject]$props

    Simple as all that.


    \_(ツ)_/

    • Marked as answer by Tony Sm(IT)h Monday, February 18, 2019 7:51 PM
    Monday, February 18, 2019 4:37 PM

All replies

  • I don't know of an alternative.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Monday, February 18, 2019 4:02 PM
  • Hi Richard,

    it's a relief to hear that smart Its don't have an alternative. Just kidding :) Thanks, then I think I will take the ugly way:

    if ($prop1) {
    
    Add
    
    }
    if ($prop2) {
    
    Add
    
    }
    .
    .
    .


    Monday, February 18, 2019 4:11 PM
  • Or do it using PwoerSHell.

    $props = @{}
    if($Name){$props.Add('Name',$name)}
    if($group){$props.Add('Group', $group)}
    $obj = [pscustomobject]$props

    Simple as all that.


    \_(ツ)_/

    • Marked as answer by Tony Sm(IT)h Monday, February 18, 2019 7:51 PM
    Monday, February 18, 2019 4:37 PM
  • Hi jrv,

    that is the closest to what I needed. Thanks for helping out!

    Cheers

    Monday, February 18, 2019 7:51 PM