PowerShell: Skip name/value-pair while creating hashtable if value is null or empty

431 Views Asked by At

Hello everybody and first of all: thanks for reading my question!

I'm struggling creating a nested hashtable for later convertto-json-object for an Invoke-RestMethod.

My simplified code at the moment is:

@{
  "NameOfArray" = @(
    @{
      "name" = "first name"
      "value" = "first value"
    }, 
    $( If ( -Not [string]::IsNullOrEmpty($VariableThatMayBeNullOrEmpty) ) {
      @{
        "name"  = "second name"
        "value" = $VariableThatMayBeNullOrEmpty
      }
    } ),
    @{
      "name" = "third name"
      "value" = "third value"
    }
  )
} | ConvertTo-Json

This is the output:

{
    "NameOfArray":  [
                        {
                            "value":  "first value",
                            "name":  "first name"
                        },
                        {

                        },
                        {
                            "value":  "third value",
                            "name":  "third name"
                        }
                    ]
}

There's an empty item in the "NameOfArray"-Array, which i would like to skip being created - if the value is null or empty...

Some part of the If-Case seems to be working, because that item is empty in a way... but it does exist and i don't want it to. :/

My preferred output should look like this:

{
    "NameOfArray":  [
                        {
                            "value":  "first value",
                            "name":  "first name"
                        },
                        {
                            "value":  "third value",
                            "name":  "third name"
                        }
                    ]
}

With the empty item being absent (if value is null or empty).

Any ideas?

Any help is highly appreciated!

Thanks in advance!

Kind Regards BaBa

1

There are 1 best solutions below

1
On BEST ANSWER

Remove the explicit subexpression $() surrounding the if statement, and then remove the , array operators - the surrounding array-expression operator @() will take care of turning the whole thing into an array anyway:

@{
  "NameOfArray" = @(
    @{
      "name" = "first name"
      "value" = "first value"
    } 
    if( -Not [string]::IsNullOrEmpty($VariableThatMayBeNullOrEmpty) ) {
      @{
        "name"  = "second name"
        "value" = $VariableThatMayBeNullOrEmpty
      }
    }
    @{
      "name" = "third name"
      "value" = "third value"
    }
  )
} | ConvertTo-Json