I am picking information from CSV file and i have mentioned tags like @{"R"="red";"B"="Blue"}. when i am assigning tags value to variable , it is printing on same format but while adding tags to vm i am getting below error ,
Set-AzResource : Cannot bind parameter 'Tag'. Cannot convert the "System.Collections.Hashtable" value of type "System.String" to
$tags| convertfrom-stringdata
but the problem is after running add tag command for Vm , it is adding tag like below @{"r : ="red";"B"="Blue"}
How can i add both tag as a separate like r:red b:blue
$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
If I understand the question, in your CSV file, there is a column called vmtags
. The values in that column are strings in the form of @{"R"="red";"B"="Blue"}
.
The Get-AzResource
cmdlet wants a Hashtable object for its -Tags
parameter. I think you took the description MS gives: Key-value pairs in the form of a hash table. For example: @{key0="value0";key1=$null;key2="value2"} a bit too literal there and now you need to create an actual Hashtable object from its string representation.
To create a Hashtable from a string like that you can use
# create a scriptblock using the string
$scriptBlock = [scriptblock]::Create('@{"R"="red";"B"="Blue"')
# execute it to create the hashtable
$tags = (& $scriptBlock)
$tags is now a Hashtable containing
Name Value ---- ----- R red B Blue
If you need to create a Hashtable from multiple strings, do something like
$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 is now a Hashtable containing
Name Value ---- ----- R red B Blue A Alpha G green