Azure PowerShell - VM 标记报告

标签 azure powershell tags virtual-machine tagging

我有兴趣查询 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/

相关文章:

azure - 确定 Azure ML 中的预测范围

node.js - Azure Redis 缓存数据丢失?

powershell - 从子文件夹复制文件并重命名

powershell - 重新提交挂起作业 (start-job)

android - SensorTag20 错误扫描服务

Azure Functions 与 Docker 镜像错误 : Azure Functions Runtime is unreachable

azure - 无法安装同步服务。请参阅事件日志了解更多详细信息

powershell - %temp% 等不工作

c# - 获取2个html标签之间的文本c#

spring - 何时使用 Spring :url tag?