首页 > 解决方案 > 需要检查 7 个特定标签是否存在于 azure VM 列表中

问题描述

您好,我需要使用 PowerShell 检查 azure VM 列表是否有 7 个特定标签,不需要检查标签值。如果缺少 7 个标签中的任何一个,则脚本将需要编写错误并打印缺少的标签。我可以从中获取标签

$vmDetails = Get-AzVM -Name $sourceVMName -ResourceGroupName $sourceResourceGroupName
$vmTags = $vmDetails.Tags

然后我可以运行一个循环

foreach ($keyval in $vmtags.keys)

但我不确定如何在没有一堆 if 语句的情况下进行比较。我确定需要一个数组,但不记得什么是最好的。谢谢一堆。

标签: azurepowershellvirtual-machine

解决方案


假设Tags属性是hashtable您在代码中显示的,代码(伪代码,因为我没有办法测试它)可能如下所示:

# Get the base Tags needed to compare
$vmDetails = Get-AzVM -Name $sourceVMName -ResourceGroupName $sourceResourceGroupName

# Assuming the Tags property is a Hashtable
$vmTags = $vmDetails.Tags.Keys

# Get the count of Tags
$i = $vmTags.Count

# Get all existing VMs on a Resource Group
$allVMs = Get-AzVM -ResourceGroupName $sourceResourceGroupName

foreach($vm in $allVMs)
{
    # Store the Tags of this VM
    $thisVMtags = $vm.Tags.Keys

    # If the count of Tags of this VMs is not the same as the count of Base Tags
    if($thisVMtags.Count -ne $i)
    {
        # Get the missing Tags of this VM
        $missingTags = $vmTags.where({
            $_ -notin $thisVMtags
        }) -join ', '

        # Write a warning with details of this VM Name and the missing Tags
        Write-Warning "{0} is missing the following Tags: {1}" -f $vm.Name, $missingTags
    }
}

推荐阅读