我有兴趣查询 Azure 订阅以提供标记报告,其中指示 VM 名称、Azure 区域以及每个 VM 的标签和标签值。
我当前的脚本为我提供了除每个标签的标签值之外的所有数据。我的输出显示的结果就好像标签不存在一样。
有人对我的剧本有什么建议吗?谢谢!
param( [Parameter(Mandatory = $true)] [String] $subscriptionName )
Select-AzSubscription -Subscription $subscriptionName
$allTags = Get-AzTag
$allVMs = Get-AzVM
$vmInformation = @() foreach ($vm in $allVMs) {
$vmInformationObject = New-Object PSObject $vmName = $vm.Name $vmRegion = $vm.Location $vmInformationObject | Add-Member -MemberType NoteProperty -Name "VM_Name" -Value $vmName $vmInformationObject | Add-Member -MemberType NoteProperty -Name "VM_Region" -Value $vmRegion $vm_tags = $vm.tags foreach ($tag in $allTags) { $IfTagExists = $false foreach ($vmtag in $vm_tags) { if ($tag.name -like $vmtag.keys) { $IfTagExists = $true $vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name) break } } if ($IfTagExists -eq $false) { $vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value "--" } } $vmInformation += $vmInformationObject }
$vmInformation | Export-Csv "path.csv" -NoTypeInformation -Force
最佳答案
这里的问题是比较语句$tag.name -like $vmtag.keys
。由于左侧值是标量,右侧值是集合或列表,因此您需要使用包含 comparison operator 。最简单的选项是 -in
或 -contains
。
# Option 1
# Use -in when singular item is on the LHS and collection is on RHS
if ($tag.name -in $vmtag.keys) {
$IfTagExists = $true
$vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name)
break
}
# Option 2
# Use -contains when singular item is on the RHS and collection is on LHS
if ($vmtag.keys -contains $tag.name) {
$IfTagExists = $true
$vmInformationObject | Add-Member -MemberType NoteProperty -Name $tag.Name -Value $vmtag.$($tag.Name)
break
}
关于Azure PowerShell - VM 标记报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66339045/