这可能非常棘手,您必须仔细确定要查找的拼写错误才能将名称更改为有效的。
可能是这样的
# 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