Home > OS >  Export Azure VM Tags along other details to CSV
Export Azure VM Tags along other details to CSV

Time:08-03

Is there a way to get all tags assigned to VM in 1 cell when exported as CSV along other details of the VM? In the column where Tags are supposed to go all I get is a single curly bracket "{"

Import-Module Az.Automation
Import-Module Az.Compute
Import-Module Az.Storage
$resourceGroup = "rg-ServerList"
$storageAccount = "stxxxxxxxxxxxxx"
$subscriptionid = "xxxxxxxxxxxxxxxxxxxxx"
$storageAccountContainer = "azure2"



#Connect-AzAccount -Identity

$date = get-date -format dd-MM-yyyy



    Set-AzContext -SubscriptionId $subscriptionid
        get-azVM -Name "MyServer" | Select @{Name="ID"; Expression={$_.vmid}},
        @{N='Subscription'; E={$Subscription}},
        @{Name="VM Name"; Expression={$_.name}},
        @{ N='Tags'; E={$_.tags | ConvertTo-Json | Out-String}} | export-csv C:\temp\Azure-servers.csv -notypeinformation
       
Set-AzContext -SubscriptionId $subscriptionid
Set-AzCurrentStorageAccount -StorageAccountName $storageAccount -ResourceGroupName $resourceGroup
Set-AzStorageBlobContent -Container $storageAccountContainer -file Azure-servers.csv -force



CodePudding user response:

You would have to form a string from the tags property which is a hashtable.

Below I use GetEnumerator() to iterate over each key value pair and create a string in <key> = <value> format then join each of the strings with a ,

Get-AzVM |
    Select-Object -Property (
        @{name='ID' ; expression={$_.VmId}},
        @{name='Subscription' ; expression={$subscription}},
        @{name='VMName' ; expression={$_.Name}},
        @{name='Tags'; expression = {($_.tags.GetEnumerator().ForEach({ '{0} = {1}' -f $_.key, $_.value }) -join ',')}}
    )
  • Related