使用Powershell批量为Azure资源添加Tags

发布时间:2020-04-11 04:30:52 作者:wuyvzhang
来源:网络 阅读:1223


在使用Azure的过程中,我们可以将Tags应用于Azure资源,从而可以将元数据逻辑的组织到某些分类中。每个Tags由名称和值组成。例如,我们可以将名称“Environment”和值“Production”应用于生产中的所有资源。

应用Tags以后,我们可以使用该Tags名称和值检索订阅中的所有资源。使用Tags可以从不同的资源组中检索相关资源。当我们需要组织用于计费或管理的资源时,此方法很有用。

需要注意的是当我们使用TagsTags资源的时候是有如下限制的:

要将Tags应用于资源,用户必须具有对该资源类型的写入权限。要将Tags应用于所有资源类型,请使用Contributor角色。要仅将Tags应用于一种资源类型,请使用该资源的Contributor角色。

说了这么多,下面我们就一起来看下如何使用Powershell批量为资源组下的所有资源添加Tags:

    #Login to Azure    
    Login-AzureRmAccount -Environment AzureChinaCloud
    #获取资源组名称(可单个也可所有)
    $Resources = Get-AzureRmResource -ResourceGroupName “ResourceGroupName”
    #对于每个资源,应用资源组的标记
    Foreach ($resource in $Resources)
    {
    $Rgname = $resource.Resourcegroupname
    $resourceid = $resource.resourceId
    $RGTags = (Get-AzureRmResourceGroup -Name $Rgname).Tags
    $resourcetags = $resource.Tags
    If ($resourcetags -eq $null)
    {
    Write-Output "---------------------------------------------"
    Write-Output "将下列标签应用到: $($resourceid)" $RGTags
    Write-Output "---------------------------------------------"
    $Settag = Set-AzureRmResource -ResourceId $resourceid -Tag $RGTagS -Force
    }
    Else
    {
    $RGTagFinal = @{}
    $RGTagFinal = $RGTags
    Foreach ($resourcetag in $resourcetags.GetEnumerator())
    {
    If ($RGTags.Keys -inotcontains $resourcetag.Key)
    {
    Write-Output "------------------------------------------------"
    Write-Output "键不存在于RG标签中添加到哈希表中" $resourcetag
    Write-Output "------------------------------------------------"
    $RGTagFinal.Add($resourcetag.Key,$resourcetag.Value)
    }
    }
    Write-Output "---------------------------------------------"
    Write-Output "将下列标签应用到:$($resourceid)" $RGTagFinal
    Write-Output "---------------------------------------------"
    $Settag = Set-AzureRmResource -ResourceId $resourceid -Tag $RGTagFinal -Force
    }
    }


推荐阅读:
  1. Azure实践之如何批量为资源组虚拟机创建alert
  2. Powershell 批量重命名

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

云计算 云服务 ers

上一篇:collections.sort对javabean的list

下一篇:Asp.net forms authentication ticket userdata is empty

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》