簡體   English   中英

PowerShell:如果值為 null 或為空,則在創建哈希表時跳過名稱/值對

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

大家好,首先:感謝您閱讀我的問題!

我正在努力為 Invoke-RestMethod 創建一個嵌套的哈希表,以便稍后轉換為 json-object。

我目前的簡化代碼是:

@{
  "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

這是輸出:

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

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

“NameOfArray”-Array 中有一個空項目,我想跳過它的創建過程-如果值為 null 或空...

If-Case 的某些部分似乎正在工作,因為該項目在某種程度上是空的……但它確實存在,我不希望它存在。 :/

我的首選輸出應如下所示:

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

不存在空項目(如果值為 null 或為空)。

有任何想法嗎?

任何幫助表示高度贊賞!

提前致謝!

親切的問候巴巴

刪除if語句周圍的顯式子表達式$() ,然后刪除,數組運算符 - 周圍的數組表達式運算符@()無論如何都會負責將整個事物轉換為數組:

@{
  "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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM