Azure PowerShell数组对象转哈希表及输出异常问题求助
Hey there! Let's figure out why your hash table conversion is throwing that weird output and get your script working properly.
First, let's clear up a common mix-up with the Get-AzureRmTag cmdlet: when you run Get-AzureRmTag -Name $Environment -Detailed, you're getting metadata about the tag itself (like how many resources use it, and a list of associated resource IDs) — not the actual resource objects you need to pull version numbers from. That's part of why your hash table is ending up with unexpected content.
Second, your ForEach-Object logic has a syntax issue: $inputobject.$_ isn't how you reference properties of the current item in the pipeline. Inside ForEach-Object, you should use $_ (or $PSItem) to refer to the current object being processed.
Let's fix this step by step:
Step 1: Get the right resources
Instead of fetching tag metadata first, directly get all resources that have your target tag using Get-AzureRmResource. This gives you the actual resource objects you need to extract version info from:
# Initialize an empty hash table $SiteList = @{} # Replace $EnvValue with the actual value of your Environment tag (e.g., "Production") $taggedResources = Get-AzureRmResource -Tag @{ Environment = $EnvValue }
Step 2: Build your hash table correctly
Now loop through each resource, pull the site name (or whatever key you want) and its version number. I'm assuming your version is stored in a tag called Version — adjust this to match where your version data lives (could be a resource property too):
$taggedResources | ForEach-Object { # Check if the Version tag exists to avoid null entries if ($_.Tags.ContainsKey('Version')) { # Use the resource name as the hash table key, version as the value $SiteList[$_.Name] = $_.Tags['Version'] } else { # Optional: Handle resources missing the Version tag $SiteList[$_.Name] = "No version tag found" } }
Step 3: Output the hash table properly
Now when you call $SiteList, it should display your key-value pairs correctly. If you want a cleaner formatted view, use:
$SiteList | Format-Table -AutoSize
If you do need to use Get-AzureRmTag first
If you specifically need to start with tag details (e.g., you only have the tag key and need to get all associated resources), you can do this instead:
$SiteList = @{} $tagDetails = Get-AzureRmTag -Name $Environment -Detailed # Loop through each resource ID linked to the tag $tagDetails.Properties.Resources | ForEach-Object { $resource = Get-AzureRmResource -ResourceId $_ if ($resource.Tags.ContainsKey('Version')) { $SiteList[$resource.Name] = $resource.Tags['Version'] } } $SiteList
The main issues in your original code were:
- Using
Get-AzureRmTagwhen you needed resource objects instead of tag metadata - Incorrectly referencing
$inputobject.$_instead of using$_to access the current item's properties
Give these adjustments a try and your hash table should output correctly!
内容的提问来源于stack exchange,提问作者RaptorJesus

