如何从 power shell 数组中删除对象?
How to remove object from array in power shell?
我正在尝试从数组中删除完整的对象而不是 object.I 我无法找到删除对象的方法有很多解决方案可用于删除该项目。
有人可以建议一种删除完整对象的方法吗?
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'){
= $_.id
Write-Host
###Here I want to remove the whole object related to the id
}}
我觉得评论里的答案就是你要找的: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
变量中。如果该语句的计算结果为假,则它会丢弃集合中的该项目并继续进行下一项。
我正在尝试从数组中删除完整的对象而不是 object.I 我无法找到删除对象的方法有很多解决方案可用于删除该项目。 有人可以建议一种删除完整对象的方法吗?
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'){
= $_.id
Write-Host
###Here I want to remove the whole object related to the id
}}
我觉得评论里的答案就是你要找的: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
变量中。如果该语句的计算结果为假,则它会丢弃集合中的该项目并继续进行下一项。