Getting null hash value while matching key using powershell

北城以北 提交于 2020-06-17 10:01:08

问题


I am trying to get the value of the key by matching key name(ignoring the white and character case).

Code :

$tagHash = (Get-AzResourceGroup -Name "twmstgmsnp").Tags
Write-Host "Resource Group tags key : " $tagHash.Keys
Write-Host "Resource Group tags value : " $tagHash.Values
$ownervalue = $tagHash.GetEnumerator() | ? {($_.Key).ToString().Replace(' ','') -eq 'CreatedBy'} | % Value
Write-Host "Resource Group CREATEDBY tag : " $ownervalue

Result :

Resource Group tags key : PURPOSE Created By 

Resource Group tags value : QA MS Team2 env Shubham Mishra

Resource Group CREATEDBY tag :

Note : It should always fetch the value if the key should have the text 'createdby'. Whether the key is 'Created By', 'Created By ', 'CREATEDBY', 'CREATED BY'. It should ignore the key white space and case.


回答1:


My guess is that you can get the exact name for the key easiest by replacing all whitespace from it first and next compare it to CreatedBy.
No need for the GetEnumerator() method, simply get the key name from the .Keys array:

$ownerKey = $tags.Keys | Where-Object { ($_ -replace '\s') -eq 'CreatedBy'}
Write-Host "Resource Group CREATEDBY Tag   : $ownerKey"
Write-Host "Resource Group CREATEDBY Value : $($tags[$ownerKey])"

Output:

Resource Group CREATEDBY Tag   :  Created By
Resource Group CREATEDBY Value :  Shubham Mishra

By default the -eq operator works case-insensitive. If you need case-sensitive comparison somewhere else, use -ceq




回答2:


If you read what your 4th and 5th lines are doing in plain text, it might make more sense where things have gone wrong.

Line 4:
Put all this in a variable: Get the enumerator from $tagHash and then get all the Keys like "Created By" and then for each match Value.

$ownervalue = $tagHash.GetEnumerator() | ? {($_.Key).ToString().Replace(' ','') -eq 'CreatedBy'} | % Value

Line 5:
Write the variable to the host window.

Write-Host "Resource Group CREATEDBY tag : " $ownervalue

This is what you want it to say in plain text:
Get the enumerator from $tagHash and then get all the Keys like "Created By" and then for each match write the value to the host window.

$tagHash.GetEnumerator() | Where-Object { $_.Key -like '*Created*By*'} | For-Each
{
    Write-Host "Resource Group CREATEDBY tag : " $_.Value
}


来源:https://stackoverflow.com/questions/61541666/getting-null-hash-value-while-matching-key-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!