【问题标题】:How to remove object from array in power shell?如何从PowerShell中的数组中删除对象?
【发布时间】:2017-12-04 19:10:01
【问题描述】:

我正在尝试从数组中删除整个对象,而不是对象的成员。我无法找到删除对象的方法,有很多解决方案可用于删除该项目。 有人可以建议一种删除完整对象的方法。

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'

标签: json windows powershell powershell-4.0


【解决方案1】:

我认为 cmets 中的答案正是您要寻找的: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 不匹配。如果这被评估为真,那么它允许项目通过管道,这在上面的示例中意味着它最终在 $Result 变量中。如果该语句的计算结果为 false,则它会丢弃集合中的该项目并继续下一个。

【讨论】:

  • 感谢您的解释。我能够读取对象并在接下来的步骤中使用数据。我想要的是当它被使用和处理完成时我想从列表中删除这个对象。可以请告诉我一种将其从列表中删除的方法。
  • 为什么需要这样做?之后你如何处理过滤后的列表?您可以使用 where cmdlet 在一个变量中创建过滤列表,同时按照您当前的方式处理它们。这有帮助吗?
  • 这是我试图将数据保存一段时间并在收到下一个请求时使用它的临时位置。在请求服务后,我想清除数组列表,因为它不再需要所以没有必要存储它。如果这个过程有什么问题,请告诉我。
  • 那么最后设置为$null?
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多