Where-Object
您可以通过(或?
简称)使用管道选择请求的项目,然后将$name
其用作查询的一部分。请记住,如果Name
属性中有重复项,结果可能会返回多个项目(在这种情况下,您可以| Select -First 1
在第一个管道之后使用)。
PS > $name = "example"
# setup of list items
PS > $x = @{}
PS > $x.Name = "example"
PS > $x.id = "j-12453634"
PS > $x.PendingShutdown = $false;
PS > $x2 = @{}
PS > $x2.Name = "other-name"
PS > $x2.id = 42
PS > $x2.PendingShutdown = $false
PS > $items = @()
PS > $items += $x
PS > $items += $x2
# displaying list before modification
PS > $items
Name Value
---- -----
PendingShutdown False
Name example
id j-12453634
PendingShutdown False
Name other-name
id 42
# selecting item from list via Name property with value from variable
PS > $items |? Name -eq $name
Name Value
---- -----
PendingShutdown False
Name example
id j-12453634
# updating item via selector from variable
PS > ($items |? Name -eq $name).PendingShutdown = $true
# displaying list after modification
PS > $items
Name Value
---- -----
PendingShutdown True
Name example
id j-12453634
PendingShutdown False
Name other-name
id 42