0

I am trying to use powershell to export all Network Security Group (NSG) rules across all subscriptions in Azure.

  $sub = Get-AzSubscription
  $sub | foreach-object {
  $null = $PSItem | Select-AzSubscription
  $null = Get-AzNetworkSecurityGroup -OutVariable +nsg
  foreach ($obj in $nsg)
  {
   $obj.SecurityRules | Select-Object -OutVariable +rules @{ n = 'NSG Name'; e = {$obj.Name}},
   @{ n = 'ResourceGroupName'; e = {$obj.ResourceGroupName}},
   *
  }
   }


 $rules | export-csv C:\Users\ABC\Desktop\NSG.csv

However, the exported csv files has many field with "System.Collections.Generic.List`1[System.String]", even though I can see the for loop is running fine and all the data is generated.

I am very new to powershell so any help on this would be much appreciated.

Head and toes
  • 659
  • 3
  • 11
  • 29

1 Answers1

0

If an object you export as CSV with Export-Csv or ConvertTo-Csv has property values that contain a collection (array) of values, these values are stringified via their .ToString() method, which results in an unhelpful representation.

Assuming you want to represent all values of an array-valued property in a single CSV column, to fix this problem you must decide on a meaningful string representation for the collection as a whole and implement it using Select-Object with a calculated property:

E.g., you can use the -join operator to create a space-separated list of the elements:

$obj.SecurityRules | Select-Object -OutVariable +rules @{ n = 'NSG Name'; e = {$obj.Name -join ' '}}, @{ n = 'ResourceGroupName'; e = {$obj.ResourceGroupName -join ' '}},*

For more details, you could refer to this SO thread.

Joey Cai
  • 18,968
  • 1
  • 20
  • 30