Azure Powershell 从 CSV 文件标记 VM

标签 azure powershell tags tagging

我对 Powershell 脚本编写还很陌生。我正在尝试从 CSV 文件生成 azure 虚拟机的标签。

在 CSV 中,我有以下列标题:

  • 虚拟机名称
  • 申请
  • 子目录
  • 环境
  • 应用程序所有者
  • 地点

我有一个测试 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

最佳答案

好的,首先:如果没有 ResourceGroupName,您将无法执行此操作,将其添加到您的案例中的最佳方法是将其作为 csv 中的一列。

其次,每个人都有自己的起点,所以永远不要道歉。 :) 我对下面代码中修复的大部分问题进行了评论。您最大的问题是 a) 您实际上并未从 CSV 加载数据(您只创建了一个包含文件路径的变量),b) 您试图使用 $ResourceID填充它。

我清理了一些东西,现在它可以工作了,如果找不到虚拟机,将会抛出错误。以下是我的 test.csv 的内容,其中包括一台正常的虚拟机和一台不存在的虚拟机。

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)!"
    }
}

关于Azure Powershell 从 CSV 文件标记 VM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58345592/

相关文章:

azure - 使用 Azure AD 与服务器进行 React-Native 身份验证

javascript - 适用于 Azure OAuth 的 ADAL - 使用 POST 重定向

azure - 当我浏览 azure iot hub 教程时,创建结束时出现错误分区计数 4 - 为什么?

MySQL合并标签记录

android - 可以在 Google Analytics 中为 Android 应用创建虚拟网页浏览吗?

azure - 一次性为所有虚拟机分配标签

azure - 如何将自定义日志转发到 Azure Sentinel

powershell - 将文件复制到远程服务器,在Powershell中加入本地和远程服务器复制文件的路径时出现问题

powershell - 如何使用 -split 运算符,同时仍然保留用于拆分字符串的子字符串?

powershell - 将密码传递到-credential