Lynchie
Lynchie

Reputation: 1149

powershell failing to list AzResourceGroup name in script

Pretty green to this powershell thing but I have a script I'm trying to rewrite (for educational purposes) that requires the manual entry of the resourcegroups in AZ into a variable that is then looped (it removes said resource groups).

$_names = 'dmz-dev-mgmt', 'dmz-dev-container','dmz-dev-governance', 'dmz-dev-global-dns','dmz-dev-automation','dmz-dev-consumption','dmz-dev-network','NetworkWatcherRG'

I so far have the following

az login

Connect-AzAccount -Subscription "DEV Data Platform"

Get-AzResourceGroup |select ResourceGroupName

If I run these commands individually in powershell they all run fine, if I run the script itself after doing the Connect-AzAccount it fails to then return the Get-AzResourceGroup

I wish to return this list via the script to the $_names variable

Is this possible?

Upvotes: 0

Views: 233

Answers (1)

Ansuman Bal
Ansuman Bal

Reputation: 11401

You can use the below to get all the resource group names and then pass it as a variable to other script and use it as per your requirement:

getresources.ps1

function ResourceGroups
{
$rgs=Get-AzResourceGroup 
return $rgs.ResourceGroupName
}
##to display the result if required
foreach ($x in ResourceGroups){
$x
}

deletegroup.ps1

Write-Host ("The acquired list of resource group names is as below:")
. .\getresources.ps1;$_names=ResourceGroups
Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
foreach($_name in $_names){
$delete= az group delete --name $_name
Write-Host "Resource Group $_name Deleted Successfully!!!"
}

Note : I have kept both the scripts in one location thats why used this line . .\getresources.ps1;$_names=ResourceGroups in the second script if you have kept them in different location then you have to load it using . .\path\to\script1.ps1;$_names=ResourceGroups

Output:

After doing az login and connect-azaccount I ran the scripts as below:

enter image description here

enter image description here enter image description here


Single script :

Write-Host ("The acquired list of resource group names is as below:")
$rgs=Get-AzResourceGroup 
$rgs.ResourceGroupName
Write-Host ("Starting the Delete operation on the above aquired Resource Groups!!")
foreach($_name in $rgs.ResourceGroupName){
$delete= az group delete --name $_name
Write-Host "Resource Group $_name Deleted Successfully!!!"
}

Upvotes: 1

Related Questions