如何在使用 powershell 获取值时忽略哈希键中的白色 space
How to ignore white space in the hash key while getting value using powershell
我正在尝试获取散列键的值。当密钥完全匹配时,它工作正常。但是,由于在密钥中找到任何 space,它会出错。
工作正常:
$tagHash = (Get-AzResourceGroup -Name "twmstgmsnp").Tags
$datevalue = $tagHash.GetEnumerator() | ? Key -eq Date | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
我试图忽略 space 中的键 :
$tagHash = (Get-AzResourceGroup -Name "twmstgmsnp").Tags
$datevalue = $tagHash.GetEnumerator() | ? Key -eq 'Date'.Replace(' ','') | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
错误:实际上我的 $datevalue 是空的,因为没有得到值。
You cannot call a method on a null-valued expression.
这是一种方法:
$data = @{ "aaa" = "bbb"; "c c c" = "ddd" }
$search = "ccc"
$matches = $data.Keys | where-object { $_.Replace(" ", "") -eq $search }
# c c c
$values = $data[$matches]
# ddd
请注意,您可能 获得多个匹配项,因此在这种情况下您需要计算出您想要的值 - 例如:
$data = @{ "aaa" = "bbb"; "c c c" = "ddd"; "ccc" = "eee" }
$search = "ccc"
$matches = $data.Keys | where-object { $_.Replace(" ", "") -eq $search }
# ccc
# c c c
$values = $data[$matches]
# eee
# ddd
如果我没有误解你的意思,你想得到值,例如当密钥像D a t e
时,如果是这样,你可以使用下面的命令。
$tagHash = (Get-AzResourceGroup -Name "<group-name>").Tags
$datevalue = $tagHash.GetEnumerator() | ? {($_.Key).ToString().Replace(' ','') -eq 'Date'} | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
门户中的标签如下:
我正在尝试获取散列键的值。当密钥完全匹配时,它工作正常。但是,由于在密钥中找到任何 space,它会出错。 工作正常:
$tagHash = (Get-AzResourceGroup -Name "twmstgmsnp").Tags
$datevalue = $tagHash.GetEnumerator() | ? Key -eq Date | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
我试图忽略 space 中的键 :
$tagHash = (Get-AzResourceGroup -Name "twmstgmsnp").Tags
$datevalue = $tagHash.GetEnumerator() | ? Key -eq 'Date'.Replace(' ','') | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
错误:实际上我的 $datevalue 是空的,因为没有得到值。
You cannot call a method on a null-valued expression.
这是一种方法:
$data = @{ "aaa" = "bbb"; "c c c" = "ddd" }
$search = "ccc"
$matches = $data.Keys | where-object { $_.Replace(" ", "") -eq $search }
# c c c
$values = $data[$matches]
# ddd
请注意,您可能 获得多个匹配项,因此在这种情况下您需要计算出您想要的值 - 例如:
$data = @{ "aaa" = "bbb"; "c c c" = "ddd"; "ccc" = "eee" }
$search = "ccc"
$matches = $data.Keys | where-object { $_.Replace(" ", "") -eq $search }
# ccc
# c c c
$values = $data[$matches]
# eee
# ddd
如果我没有误解你的意思,你想得到值,例如当密钥像D a t e
时,如果是这样,你可以使用下面的命令。
$tagHash = (Get-AzResourceGroup -Name "<group-name>").Tags
$datevalue = $tagHash.GetEnumerator() | ? {($_.Key).ToString().Replace(' ','') -eq 'Date'} | % Value
Write-Host "Resource Group Date tag : " $datevalue.Replace(' ','')
门户中的标签如下: