【问题标题】:Azure Tags issueAzure 标记问题
【发布时间】:2020-04-28 03:05:43
【问题描述】:

我正在从 CSV 文件中挑选信息,并且我提到了 @{"R"="red";"B"="Blue"} 之类的标签。 当我将标签值分配给变量时,它以相同的格式打印,但是在向 vm 添加标签时,我遇到了错误,

Set-AzResource : Cannot bind parameter 'Tag'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to



$tags| convertfrom-stringdata 

但问题是在为 Vm 运行 add tag 命令后,它正在添加如下标签 @{"r : ="红色";"B"="蓝色"}

如何将两个标签分别添加 r:红色 b:蓝色

$rss = Import-csv "C:\abc\VijayGupta\Desktop\Vm_build_azure.csv"
$tag = $rss.vmtags 
$tags = $tag | ConvertFrom-StringData
$vms=Get-AzResource -Name abc -ResourceGroupName Southindia
Set-AzResource -ResourceId $vms.Id -Tag $tags -Force

【问题讨论】:

    标签: powershell tags


    【解决方案1】:

    如果我理解这个问题,在您的 CSV 文件中,有一个名为 vmtags 的列。该列中的值是@{"R"="red";"B"="Blue"} 形式的字符串。

    Get-AzResource cmdlet 需要一个 Hashtable 对象作为其 -Tags 参数。我认为您接受了 MS 给出的描述:哈希表形式的键值对。例如:@{key0="value0";key1=$null;key2="value2"} 有点太字面了,现在你需要从它的创建一个实际的 Hashtable object字符串表示。

    要从这样的字符串创建哈希表,您可以使用

    # create a scriptblock using the string
    $scriptBlock = [scriptblock]::Create('@{"R"="red";"B"="Blue"')
    # execute it to create the hashtable
    $tags = (& $scriptBlock)
    

    $tags 现在是一个包含

    的哈希表
    Name                           Value
    ----                           -----
    R                              red
    B                              Blue
    

    如果您需要从多个字符串创建一个 Hashtable,请执行类似的操作

    $vmtags = '@{"R"="red";"B"="Blue"}', '@{"G"="green";"A"="Alpha"}'
    
    # first loop creates the hashtables from the individual strings
    $arr = $vmtags | ForEach-Object {
        $scriptBlock = [scriptblock]::Create($_)
        & $scriptBlock
    }
    
    # the second loop merges all Hashtables in the array into one
    $tags = @{}
    $arr | ForEach-Object {
        foreach ($key in $_.Keys) {
            $tags[$key] = $_.$key
        }
    }
    

    $tags 现在是一个包含

    的哈希表
    Name                           Value
    ----                           -----
    R                              red
    B                              Blue
    A                              Alpha
    G                              green
    

    【讨论】:

    • 非常感谢您的上述建议,将尝试按照给定的步骤进行操作
    猜你喜欢
    • 2012-03-28
    • 2023-03-08
    • 2014-08-24
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多