简体   繁体   English

使用 powershell 将 NSG 规则导出到 csv 文件

[英]Export NSG rules to a csv file using powershell

I am trying to use powershell to export all Network Security Group (NSG) rules across all subscriptions in Azure.我正在尝试使用 powershell 在 Azure 中的所有订阅中导出所有网络安全组 (NSG) 规则。

  $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.但是,导出的 csv 文件有许多带有“System.Collections.Generic.List`1[System.String]”的字段,尽管我可以看到 for 循环运行良好并且生成了所有数据。

I am very new to powershell so any help on this would be much appreciated.我对 powershell 非常陌生,因此非常感谢您对此的任何帮助。

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.如果您使用Export-CsvConvertTo-Csv导出为 CSV 的对象具有包含值集合(数组)的属性值,则这些值将通过其.ToString()方法进行字符串化,这会导致表示无用。

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 :假设您想在单个 CSV 列中表示数组值属性的所有值,要解决此问题,您必须为整个集合确定一个有意义的字符串表示形式,并使用Select-Object计算属性来实现它:

Eg, you can use the -join operator to create a space-separated list of the elements:例如,您可以使用 -join 运算符来创建以空格分隔的元素列表:

$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 .有关更多详细信息,您可以参考此SO thread

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM