我正在尝试使用 Powershell 在资源和资源组上添加标签。 问题是它删除了现有标签并添加了新标签。
Powershell 脚本:
Get-AzureRmResourceGroup "testvsoRG" | Set-AzureRmResourceGroup -Tag @{Environment="UAT";Location="USA";DNS="www.xyz.com";Timezone="PST";Phase="Live"}
$resourceGroupName="testvsoRG"
$tags_to_apply=(Get-AzureRmResourceGroup -Name $resourceGroupName).tags
Find-AzureRmResource -ResourceGroupName $resourceGroupName | foreach
{
Set-AzureRmResource -ResourceId $_.resourceid -Tag $tags_to_apply -Force
}
我想要什么 假设我有 3 个标签。我将提供资源组,它应该将这 3 个标签添加到资源组及其资源中。资源组及其资源中已经有一些标签。我想保持这些标签不变,如果我的新标签与现有标签匹配,那么它应该更新它。
仅适用于资源组
$h = @{1="one";2="two";3="three"}
$resourceGroupName="testvsoRG"
$group=(Get-AzureRmResourceGroup -Name $resourceGroupName).tags
foreach ($key in $group.Keys)
{
if ($h.ContainsKey($key))
{
$group.Remove($key)
}
}
$group += $h
write-host $group
错误
System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.
Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry System.Collections.DictionaryEntry
在 Azure 资源组资源中添加标签
$resources = Get-AzureRmResource -ResourceGroupName $resourceGroupName
foreach ($r in $resources)
{
$resourcetags = (Get-AzureRmResource -ResourceId $r.ResourceId).Tags
foreach ($rkey in $resourcetags.Keys)
{
if ($h.ContainsKey($rkey))
{
$resourcetags.Remove($rkey)
}
}
$resourcetags += $h
Set-AzureRmResource -Tag $resourcetags -ResourceId $r.ResourceId -Force
}
错误
Get-AzureRmResource : Parameter set cannot be resolved using the specified named parameters.
最佳答案
如果使用 $tags_to_apply=(Get-AzureRmResourceGroup -Name $resourceGroupName).tags
,则 $tags_to_apply
将是一个哈希表。
The resource group and its resource already have some tags in it. I want to keep those tags as it is and if my new tags matches the existing ones then it should update it.
根据我的理解,您想在哈希表中添加新项目,如果该项目已存在于哈希表中,则更新它。你可以引用我的示例命令,在我这边运行得很好。
$hashtable = @{1="one";2="two";3="three"}
$h = @{4="four";2="two2"}
foreach($key in $($hashtable.keys)){
if ($h.ContainsKey($key)){
$hashtable.Remove($key)
}
}
$hashtable += $h
更新:
可能是由于键名的原因,混合了int
和string
造成的,我更改了键名,工作正常。
首先,设置标签
。
$resourceGroupName = "resourceGroupName"
Set-AzureRmResourceGroup -Name $resourceGroupName -Tag @{tag1="one";tag2="two2";tag3="three"}
其次,使用新的哈希表设置Tag
。
$h = @{tag2="two";tag4="four"}
$resourceGroupName="resourceGroupName"
$group=(Get-AzureRmResourceGroup -Name $resourceGroupName).Tags
foreach($key in $($group.keys))
{
if(!$key){
if ($h.ContainsKey($key)){
$group.Remove($key)
}
}
}
$group += $h
Set-AzureRmResourceGroup -Name $resourceGroupName -Tag $group
关于powershell - 使用Powershell实现资源组中资源的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920473/