Search code examples
azurepowershelltagsazure-webapps

Save tag to a storage table how to convert it as a hashtable


i'm trying to save app service tags to a storage table in this way:

$srcapp = Get-AzWebApp -ResourceGroupName "myrg" -Name "myapp"
$srcapp.Tags

$srcapp.Tags is this type:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Dictionary`2                             System.Object

i'm trying to convert it to a json to save it into table. In this way it works:

$jsonTag     = ConvertTo-Json -InputObject $srcapp.Tags

when i try to get it from table with:

$Setting = Get-AzTableRow -Table $cloudTable -PartitionKey $PartKey -RowKey mykey

i got correctly the value as a string. When i convert it:

ConvertFrom-Json -InputObject   $Setting.Tags

i got an PSCustomObject but when i pass it to new-aztag i got error:

New-AzTag: Cannot bind parameter 'Tag'. Cannot convert value "@{xxx=xxx}" value of type "System.Management.Automation.PSCustomObject" to type "System.Collections.Hashtable"."

there is way to convert it in an hashtable? I'm using powershell 5.1

Thanks


Solution

  • To convert it as a system.Collections.hashtable from system.Management.Automation.PsCustomObject, you can use the below given PowerShell command.

     ConvertTo-Hashtable -InputObject <inputdata>
    

    Note: Make sure that you've installed hash table modules. If not installed, install & import using below commands.

    Install-Module -Name ConvertTo-Hashtable
    Import-Module -Name ConvertTo-Hashtable
    

    I modified your script as below:

    $storageacc = "<StorageaccountName>"
    $key = "xxxxxx=="
    $ctx = New-AzStorageContext -StorageAccountName $storageacc -StorageAccountKey $key
    $jahnavitable = (Get-Azstoragetable -table "xxxtableName" -context $ctx).cloudtable
    $jahnavirow = Get-Aztablerow -Table $jahnavitable
    $jahnavirow.gettype()
    $convertintohash = ConvertTo-Hashtable -InputObject $jahnavirow 
    $convertintohash
    New-Aztag -ResourceID "<ResourceID>" -Tag $convertintohash
    

    I got an PSCustomObject and received the same error as shown here when I tried New-Aztag command initially.

    enter image description here

    So, I converted it to a hashtable using the convertTo-Hashtable command, and it is now system.collections.Hashtable.

    enter image description here

    And now I ran the New-AzTag command, which prompted me for the ResourceID.

    enter image description here

    Add the resourceId for which you want to add the tags and it will add successfully without any errors.

    enter image description here

    Tags are added under the given resource in the portal:

    enter image description here