簡體   English   中英

如何從Power Shell中的數組中刪除對象?

[英]How to remove object from array in power shell?

我正在嘗試從數組而不是對象的成員中刪除完整的對象。我找不到刪除對象的方法,有很多解決方案可以刪除該對象。 有人可以建議一種刪除完整對象的方法。

JSON Data: JSON data stored in the file.

{
  "data": [
    {
      "id": "Caption",
      "firstname": "Caption",
      "lastname": "test",
      "email": "test",
      "requester": "test",
      "password": "test",
      "incNumber": "test"
    }
  ]
}

Code : I have written the following code to read the object from the array and store into variables to do the task.Once the task is completed I want to remove the object from the array.

$file = Get-Content '\path\to\file' -Raw | ConvertFrom-Json
$file.data | % {if($_.id -eq 'Caption'){
        $1 = $_.id
        Write-Host $1
        ###Here I want to remove the whole object related to the id
    }}

我認為注釋中的答案就是您要尋找的內容: file.data = $file.data | ? id -ne 'Caption' file.data = $file.data | ? id -ne 'Caption' file.data = $file.data | ? id -ne 'Caption'

為此,它使用? 這實際上是Where-Object cmdlet的別名(替代名稱),當您要基於某些條件(非常熟悉SQL的WHERE語句)來過濾集合時,將使用此別名。

上面的答案是一個簡短的版本,您可能會看到以下內容:

$file = Get-Content '\path\to\file' -Raw | ConvertFrom-Json
$Result = $file.data | Where-Object {$_.id -ne 'Caption'}

它將ScriptBlock { }傳遞給Where-Object cmdlet,並使用$_代表管道中的每個項目,然后使用-ne作為不等於比較運算符,以查看該對象的ID屬性是否與字符串Caption不匹配。 。 如果將其評估為true,則它允許該項目通過管道,這在上面的示例中意味着它最終在$Result變量中。 如果該語句的評估結果為false,則它將丟棄集合中的該項目,然后移至下一個項目。

暫無
暫無

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

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