azure - 需要检查 7 个特定标签是否存在于 azure VM 列表中
问题描述
您好,我需要使用 PowerShell 检查 azure VM 列表是否有 7 个特定标签,不需要检查标签值。如果缺少 7 个标签中的任何一个,则脚本将需要编写错误并打印缺少的标签。我可以从中获取标签
$vmDetails = Get-AzVM -Name $sourceVMName -ResourceGroupName $sourceResourceGroupName
$vmTags = $vmDetails.Tags
然后我可以运行一个循环
foreach ($keyval in $vmtags.keys)
但我不确定如何在没有一堆 if 语句的情况下进行比较。我确定需要一个数组,但不记得什么是最好的。谢谢一堆。
解决方案
假设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
}
}
推荐阅读
- esp8266 - ESP8266-01 从 Arduino IDE 加载但不运行
- html - 为什么没有显示 CSS 文件?
- ruby - 如何在 Hanami 中使用一个 SQL 查询从多个表中获取数据?
- c# - 将常量 Collection 绑定到 ComboBox 和 SelectedItem 到 TextBox
- php - CF7 - 根据数据库验证 textarea 表单字段中的序列号列表
- c# - C# - 将对象的分区列表分成不同大小的分区
- c - Cs50 pset1-cash 应为“18\n”,而不是“22\n”
- python-3.x - 如何使用逻辑运算符从具有 categoricalDtype 的列中选择 pandas 数据框中的行
- java - 有人可以帮助解释这两个线程的输出吗?
- ios - 无法在 Xamarin iOS 上使用自定义字体