CSV文件中的Azure Powershell标记VM

时间:2019-10-11 16:56:51

标签: azure powershell tags tagging

我对Powershell脚本非常陌生。我正在尝试从CSV文件中为Azure虚拟机生成标签。

在CSV内,我具有以下列标题:

  • VMName
  • 应用程序
  • SubCat
  • 环境
  • AppOwner
  • 位置

我有一个测试CSV,其字面上包含以下数据: MattTestVM,TestApp,TestSubapp,Dev,Matt,英国南部

我不确定我在代码中出了什么问题才能使其添加标签。

代码

#Set Credentials

$cred = Get-credential

# Sign-in with Azure account credentials

add-azurermaccount -credential $cred

# Select Azure Subscription

$subscriptionId = (Get-AzureRmSubscription | Out-GridView -Title "Select an Azure Subscription ..." -PassThru).SubscriptionId

#Select specified subscription ID

Select-AzureRmSubscription -SubscriptionId $subscriptionId



$InputCSVFilePath = "C:\test\Tagging1.csv"

#Start loop

foreach ($eachRecord in $InputCSVFilePath)

{

    $VMName = $eachrecord.VMName

    $Application = $eachrecord.Application

    $SubCat = $eachrecord.SubCat

    $Environment = $eachrecord.Environment

    $AppOwner = $eachrecord.AppOwner

    $Location = $eachrecord.Location



     $r = Get-AzureRmResource -ResourceId $ResourceId -ErrorAction Continue



    if($r -ne $null)

    {

        if($r.tags)

        {

            # Tag - Application

            if($r.Tags.ContainsKey("Application"))

            {

                $r.Tags["Application"] = $Application

            }

            else

            {

                $r.Tags.Add("Application", $Application)

            }



            # Tag - SubCat

            if($r.Tags.ContainsKey("subCat"))

            {

                $r.Tags["subCat"] = $subCat

            }

            else

            {

                $r.Tags.Add("subCat", $subCat)

            }



            # Tag - Environment

            if($r.Tags.ContainsKey("Environment"))

            {

                $r.Tags["Environment"] = $Environment

            }

            else

            {

                $r.Tags.Add("Environment", $Environment)

            }



            # Tag - AppOwner

            if($r.Tags.ContainsKey("AppOwner"))

            {

                $r.Tags["AppOwner"] = $AppOwner

            }

            else

            {

                $r.Tags.Add("AppOwner", $AppOwner)

            }



            # Tag - Location

            if($r.Tags.ContainsKey("Location"))

            {

                $r.Tags["Location"] = $Location

            }

            else

            {

                $r.Tags.Add("Location", $Location)

            }



            #Setting the tags on the resource

            Set-AzureRmResource -Tag $r.Tags -ResourceId $r.ResourceId -Force

        }

        else

        {

            #Setting the tags on a resource which doesn't have tags

            Set-AzureRmResource -Tag @{ Application=$Application; subCat=$subCat; Environment=$Environment; AppOwner=$AppOwner; Location=$Location } -ResourceId $r.ResourceId -Force

        }

    }

    else

    {

        Write-Host "Resource Not Found with Resource Id: " + $ResourceId

    }





}

错误消息

 Get-AzureRmResource : Cannot validate argument on parameter 'ResourceId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

    At line:10 char:43

    +      $r = Get-AzureRmResource -ResourceId $ResourceId -ErrorAction Co ...

    +                                           ~~~~~~~~~~~

        + CategoryInfo          : InvalidData: (:) [Get-AzureRmResource], ParameterBindingValidationException

        + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet

1 个答案:

答案 0 :(得分:0)

好吧,首先是第一件事:没有ResourceGroupName,您将无法做到这一点,在您的情况下,添加它的最佳方法是将其作为csv中的一列。

第二,每个人都从某个地方开始,所以永远不要道歉。 :)我评论了以下代码中修复的大多数问题。您最大的问题是:a)您实际上没有从CSV加载数据(您仅创建了一个带有文件路径的变量),并且b)您试图使用$ResourceID而不填充它。 / p>

我整理了一下,现在可以正常工作,如果找不到虚拟机,则会抛出错误。这是我的test.csv的内容,其中包含一台良好的VM和一台不存在的VM。

VMName,ResourceGroup,Application,SubCat,Environment,AppOwner,Location
test-rm-01,test-rg,Thing,Subs,Dev,Nick,Europe
clambake,mygroup,,,,,

这是重新编写的脚本。

# Set Credentials (Fixed this up)

$context = Get-AzureRmContext
if ($context.Account -eq $null) {
    Login-AzureRmAccount
}

# Select Azure Subscription

$subscriptionId = (Get-AzureRmSubscription | Out-GridView -Title "Select an Azure Subscription ..." -PassThru).SubscriptionId

#Select specified subscription ID

Select-AzureRmSubscription -SubscriptionId $subscriptionId

$InputCSVFilePath = "C:\Users\Nick\Desktop\test.csv"

################
#
# Here you were missing loading the actual data. Also renamed the items in the loop, nitpicking. :)
#
################

$csvItems = Import-Csv $InputCSVFilePath

################

#Start loop

foreach ($item in $csvItems)
{
    ################
    #
    # Change here, you need ResourceGroupName
    # Also cleared r because if you don't, it will still have a value if no matching VM is found, which would re-tag the previous item from the loop, instead of throwing an error that the VM was not found
    #
    ################ 

    Clear-Variable r

    $r = Get-AzureRmResource -ResourceGroupName $item.ResourceGroup -Name $item.VMName -ErrorAction Continue

    ################ 

    if ($r -ne $null)
    {
        if ($r.Tags)
        {
            # Tag - Application

            if ($r.Tags.ContainsKey("Application"))
            {
                $r.Tags["Application"] = $item.Application
            }
            else
            {
                $r.Tags.Add("Application", $item.Application)
            }

            # Tag - SubCat

            if ($r.Tags.ContainsKey("subCat"))
            {
                $r.Tags["subCat"] = $item.subCat
            }
            else
            {
                $r.Tags.Add("subCat", $item.subCat)
            }

            # Tag - Environment

            if ($r.Tags.ContainsKey("Environment"))
            {
                $r.Tags["Environment"] = $item.Environment
            }
            else
            {
                $r.Tags.Add("Environment", $item.Environment)
            }

            # Tag - AppOwner

            if ($r.Tags.ContainsKey("AppOwner"))
            {
                $r.Tags["AppOwner"] = $item.AppOwner
            }
            else
            {
                $r.Tags.Add("AppOwner", $item.AppOwner)
            }

            # Tag - Location

            if ($r.Tags.ContainsKey("Location"))
            {
                $r.Tags["Location"] = $item.Location
            }

            else
            {
                $r.Tags.Add("Location", $item.Location)
            }

            #Setting the tags on the resource

            Set-AzureRmResource -Tag $r.Tags -ResourceId $r.ResourceId -Force
        }

        else
        {
            #Setting the tags on a resource which doesn't have tags

            Set-AzureRmResource -Tag @{ Application = $Application; subCat = $subCat; Environment = $Environment; AppOwner = $AppOwner; Location = $Location } -ResourceId $r.ResourceId -Force
        }
    }
    else
    {
        Write-Host "No VM found named $($item.VMName) in ResourceGroup $($item.ResourceGroup)!"
    }
}