我试图从数组中删除整个对象而不是对象的成员。我无法找到删除对象的方法,有太多可用于删除项目的解决方案。 有人可以建议一种方法删除整个对象。
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
}}
答案 0 :(得分:0)
我认为评论中的答案正是您所寻找的: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
作为not equals比较运算符来查看是否该对象的ID
属性与字符串Caption
不匹配。如果将其评估为true,则它允许项目通过管道,在上面的示例中,它意味着它最终在$Result
变量中。如果语句的计算结果为false,则它会丢弃该集合中的该项,然后继续执行下一个项目。