Reputation: 127
I am trying to list the Azure resource groups based on only the locations available in vnet locations. Here is my code.
$AllVnet=Get-AzVirtualNetwork
$SelectVnet=$AllVnet | Select-Object -Property Name,ResourceGroupName,Location
$vnetloc=$SelectVnet.Location
$ResourceGroupList=@()
foreach($loc in $vnetloc)
{
$ResourceGroup=Get-AzResourceGroup -Location $loc
$Name=$ResourceGroup.ResourceGroupName
$Loc=$ResourceGroup.Location
$VMObject = New-Object PSObject
$VMObject | Add-Member -MemberType NoteProperty -Name "Name" -Value $Name
$VMObject | Add-Member -MemberType NoteProperty -Name "Location" -Value $Loc
$ResourceGroupList += $VMObject
}
$ResourceGroupList
It returns the result in the below format
Name Location
---- --------
AZRWUSRG1 westus
{NWRG, AZREUS####, AZREU###, AZREUSLSSTO###} {eastus, eastus, eastus, eastus…}
But I want in this format
Name Location
---- --------
AZRWUSRG1 westus
NWRG eastus
AZREUS#### eastus
AZREUSLSSTO### eastus
How can I achieve that? Can anyone please help.
Upvotes: 0
Views: 801
Reputation: 27796
Get-AzResourceGroup
can return multiple objects of type PSResourceGroup
. In this case $ResourceGroup
will be an array.
$Name=$ResourceGroup.ResourceGroupName
The above code lets PowerShell create an array by collecting the value of the property ResourceGroupName
from all elements of the array $ResourceGroup
. This is why you get output like {NWRG, AZREUS####, AZREU###, AZREUSLSSTO###}
.
The code can be fixed and greatly simplified like this:
$AllVnet=Get-AzVirtualNetwork
$SelectVnet=$AllVnet | Select-Object -Property Name,ResourceGroupName,Location
$vnetloc=$SelectVnet.Location
$ResourceGroupList = foreach($loc in $vnetloc)
{
Get-AzResourceGroup -Location $loc | Select-Object Name, Location
}
Using Select-Object
we create a new object for each PSResourceGroup
element that is returned from Get-AzResourceGroup
, containing only the given properties.
Since we have assigned the foreach
output to a variable, PowerShell automatically captures all output from the loop body in the variable, which will be an array when there are more than one elements.
Upvotes: 1