Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

Displaying the content of Subnet in a form of table in PowerShell

I am trying to display the PowerShell data in the following format.

Vnet        Subnet
----        ------
AZRWUSVNET1 default
Corpvnet    MgmtSubnet 
Corpvnet    Devsubnet
Corpvnet    QASubnet 
Corpvnet    ProdSubnet

I have tried this below script

$a = Get-AzVirtualNetwork
$b = $a | Select-Object Name,Subnets
$ResourceList = @()
foreach ($item in $b)
{
  $vnetname = ($b | Where-Object -Property Name -EQ ($item.Name))
  $subnet = $vnetname.Subnets.Name
  $vnetname = $item.Name
  $VMObject = New-Object PSObject
  $VMObject | Add-Member -MemberType NoteProperty -Name "Vnet" -Value $vnetname
  $VMObject | Add-Member -MemberType NoteProperty -Name "Subnet" -Value $subnet
  $ResourceList += $VMObject
}
$ResourceList

But I am getting the data in the following format


Vnet        Subnet
----        ------
AZRWUSVNET1 default
Corpvnet    {MgmtSubnet, Devsubnet, QASubnet, ProdSubnet…}

Can anyone please help here.

question from:https://stackoverflow.com/questions/65938349/displaying-the-content-of-subnet-in-a-form-of-table-in-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simplify your code significantly by using Select-Object to extract and annotate the Subnets values:

Get-AzVirtualNetwork |Select-Object -Property @{Name='Vnet';E=
Name'} -ExpandProperty Subnets |Select-Object Vnet,@{Name='Subnet';Expression={$_.Name}}

If you insist on using loops, you'll need a nested loop (since the individual subnets are nested inside each vnet):

$vNets = Get-AzVirtualNetwork | Select-Object Name, Subnets
$ResourceList=@()

foreach($vNet in $vNets){
  foreach($subnet in $vNet.Subnets){
    $VMObject = New-Object PSObject
    $VMObject | Add-Member -MemberType NoteProperty -Name "Vnet" -Value $vNet.Name
    $VMObject | Add-Member -MemberType NoteProperty -Name "Subnet" -Value $subnet.Name
    $ResourceList += $VMObject
  }
}

$ResourceList

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...