首页 > 解决方案 > 在没有数据丢失或中断的情况下批量整合和编辑 Azure 标记?

问题描述

如何纠正以下拼写错误或有一些空格或拼写错误的 Azure 标记?

是否有任何脚本可以编辑所有标签并将其替换为正确的关键字https://docs.microsoft.com/en-us/powershell/module/az.resources/get-aztag?view=azps-4.8.0

从:

  Name        Count
  Cost-Center    750
  Cost-Centre    250
  Cost Center    250
  Cost Centre    500

进入:

   Name            Count
   Cost Center     1750

最好是散装,因此无需手动检查所有对象并手动更换。

标签: azurepowershellazure-powershell

解决方案


这可能非常棘手,您必须仔细确定要查找的拼写错误才能将名称更改为有效的。

可能是这样的

# testdata
$azTags = @"
Name,Count
Cost-Center,750
Cost-Centre,250
Cost Center,250
Cost Centre,500
Department,5
Dept,15
"@ | ConvertFrom-Csv

# find misspelled names using wildcards and replace with hardcoded correct name
$azTags | Where-Object { $_.Name -like 'Cost*Cent*' } | ForEach-Object { $_.Name = 'CostCenter' }
$azTags | Where-Object { $_.Name -like 'Dep*' } | ForEach-Object { $_.Name = 'Department' }

# group the objects and calculate the sum of all Count properties
$azTags | Group-Object Name | ForEach-Object {
    [PsCustomObject]@{
        Name = $_.Name
        Count = ($_.Group | Measure-Object -Property Count -Sum).Sum
    }
}

输出

Name       Count
----       -----
CostCenter  1750
Department    20

一个可能更好的方法是使用包含正确拼写的键和作为值的正则表达式字符串构建一个哈希表,该字符串试图匹配您遇到的所有错误拼写。(-like与上面的通配符一起使用可能太粗糙了)

当然,您必须首先获取所有坏名称的列表,然后从中找出正则表达式应该是什么来捕获它们。

例如,你可以有这个:

Name                Count
----                -----
Cost-Center           750
   Cost-Centre        250  
Cost Center           250
Cost   Centre         500
Department              5
 Dept                  15
Dpt.                    1
IT                      3
  I.T.                  6
Information Technology  4

然后下面可能会清理所有yang内容并将其替换为yin

# testdata
$azTags = @"
Name,Count
Cost-Center,750
   Cost-Centre,250  
Cost Center,250
Cost   Centre,500
Department,5
 Dept,15
Dpt.,1
IT,3
  I.T,6
Information Technology,4
"@ | ConvertFrom-Csv

# create a hashtable of correct names (yin) and a regex string containing bad matches (yang)
$hash = @{
    'CostCenter' = '^\s*Cost[^C]+Cent[re]\s*'
    'Department' = '^\s*(Dep[^a]+|Dpt\.?)\s*'
    'IT'         = '^\s*(I\.?T\.?|Information[^T]+)\s*'
}

# loop through the keys and replace the items in $azTags that match the yang
foreach ($yin in $hash.Keys) {
    $azTags | Where-Object { $_.Name -match $hash[$yin] } | ForEach-Object { $_.Name = $yin }
}

完成后,您可以按名称对项目进行分组并获取Count值的总和:

# group the objects and calculate the sum of all Count properties
$azTags | Group-Object Name | ForEach-Object {
    [PsCustomObject]@{
        Name = $_.Name
        Count = ($_.Group | Measure-Object -Property Count -Sum).Sum
    }
}

输出:

Name       Count
----       -----
CostCenter  1750
Department    21
IT            13

推荐阅读