为什么使用csv文件中的标签标记Azure VM的Powershell脚本失败?

时间:2019-07-10 08:59:14

标签: azure powershell csv tags

我正在尝试使用CSV文件中的标签来标记已部署的Azure VM。该脚本应该能够使用我的RG和VM列查找VM,从Company,DNS,CN和Type列分配标签,并替换旧的CN标签(如果它们存在)。

我找到了这个脚本,并根据需要对其进行了修改,但是我无法使其正常工作。

$csv = import-csv "C:\Powershell scripts\Tagging\Tagging.csv"

$csv | ForEach-Object {
    # Retrieve existing tags
    $tags = (Get-AzureRmResource -ResourceGroupName -Name $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM).Tags

    # Define new value pairs from CSV
    $newTags = @{
        company     = $_.Company
        dns         = $_.DNS
        type        = $_.Type
        CN          = $_.CN
    }

    # Add new tags to existing set (overwrite conflicting tag names)
    foreach($CN in $newTags.Keys){
        $tags[$_] = $newTags[$_]
    }

    # Update resource with new tag set
    Set-AzureRmResource  -ResourceGroupName -Name $_.RG -Name $_.VM -Tag $tags -ResourceType "Microsoft.Compute/virtualMachines" -verbose
}

我的CSV文件看起来像这样:

Company,DNS,Type,CN,RG,VM
CompanyOne,VM1,Test,10917,machine774_rg,machine774
CompanyTwo,VM2,Development,10917,machine776_rg,machine776
...

Powershell在尝试运行脚本时向我抛出这些错误:

Get-AzureRmResource : Missing an argument for parameter 'ResourceGroupName'. Specify a parameter of type 'System.String' and try again.
At line:3 char:34
+     $tags = (Get-AzureRmResource -ResourceGroupName -Name $_.RG -Reso ...
+                                  ~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [Get-AzureRmResource], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet

Cannot index into a null array.
At line:15 char:9
+         $tags[$_] = $newTags[$_]
+         ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray

1 个答案:

答案 0 :(得分:0)

-ResourceGroupName -Name $_.RG这部分是错误的,应该如下所示:

Get-AzureRmResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM

此外,Set-AzureRmResource命令应为:

Set-AzureRmResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM