How to get list of all Azure subscriptions and resources using powershell (in specific format) - azure

I am trying to execute below powershell script to get list of all Azure subscriptions and resource details,
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
Set-AzContext -SubscriptionId $_.SubscriptionId
Get-AzResource | Select Name,ResourceGroupName,Location,Type
} | Export-Csv azureinventory.csv
However, its just dumping the data in one column in mentioned CSV file. I need each column to display Subscription name, Subscription ID, associated resource name, resource groupname, location, Type.
Please help to update the script accordingly.

Below Script will help you to get the details of your current subscription name, tenant id, environment, account name(or select your subscription after logging) and also the resource groups in that subscription, each resource group name, type, location of each resource available in that resource group, where you can export into excel sheet with a specific format like:
Script:
$ErrorActionPreference = "Stop"
try {
Connect-AZAccount
Set-AzContext -SubscriptionName 'Your Subscription Name'
$rgs = Get-AzResourceGroup
foreach ($rg in $rgs.ResourceGroupName)
{
Write-Output "Checking Resource Group: $rg"
Get-AzResource -ResourceGroupName $rg | Select Name, ResourceGroupName, Type, Location | Export-Csv .\AzureResources.csv -Append -Force -NoTypeInformation
} }
catch {
Write-Host "$($_.Exception.Message)" -BackgroundColor DarkRed
}
And the Output is:
It will check the resource groups existing or not. After that, open the AzureResources.csv file exported in the path where you executed your script in the PowerShell.
The exported file shows the data of resource group name, each resource name, its type and location in the tabular format.

I have updated the script and it is not tested. the parameter value can be different here. Kindly change it by verifying it from Get-Azresource.
$resources = #()
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$subscriptionId = $_.SubscriptionId
Get-AzResource | ForEach-Object {
$resources += [PSCustomObject]#{
SubscriptionName = $subscriptionName
SubscriptionId = $subscriptionId
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
Location = $_.Location
}
}
}
$resources | Export-csv c:\sompeath\somename.csv

Related

Getting Subscription ID with Resource Group without setting az context

I have a tenant with multiple subscriptions.
When I first login using Connect-AzAccount, it shows a message "TenantId 'xxxxx-xxxxx-xxx-xxx' contains more than one active subscription. First one will be selected for further use. To select another subscription, use Set-AzContext."
But I want to be able to do Get-AzResourceGroup -name 'abcd'.
The problem is resource group abcd is not under the first selected subscription selected from the login command.
I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.
tried to clear the context clear-azContext but that signs me out.
I want to progromatically Get-AzResourceGroup -Name "ResourcegroupName" to retrieve the subscriptionID without setting az context as it defeats the purpose.
After reproducing from my end, Using the below script I could able to achieve your requirement.
$ResourceGroupName = Read-Host "Enter the resource group name you are searching for"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$subscriptionId = $_.SubscriptionId
Set-AzContext -SubscriptionId $subscriptionId
(Get-AzResourceGroup).ResourceGroupName | ForEach-Object {
If ($ResourceGroupName -eq $_) {
[PSCustomObject] #{
Subscription = $subscriptionName
SubscriptionId = $subscriptionId
ResourceGroup = $_
}
}
}
}
RESULTS:

Using PowerShell, How to get list of all Azure subscriptions having Azure Data factory Resource in it?

I want to retrieve the list of subscriptions having Azure Data Factory resource in it. I want to use PowerShell and get the subscription list and ADF list.
I have tried Get-AzSubscription, but it does not contain filter for resource type i.e. Microsoft.DataFactory/factories. This filter can be added to only Get-AzResource.
Get-AzSubscription Module
Get-AzResource Module
Ok here you are:
$resType = "Microsoft.DataFactory/factories"
$resTypeName = "DataFactory"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$tenantId = $_.TenantId
Set-AzContext -SubscriptionId $_.SubscriptionId -TenantId $_.TenantId
(Get-AzResource -ResourceType $ResType) | ForEach-Object {
[PSCustomObject] #{
true_sub = $subscriptionName
}
} | get-unique
} | Select-String 'true_sub' | ForEach-Object{ "Found_" + "$resTypeName" + "_In_Subscription= $($subscriptionName)"}
EDIT: Added variables to make it easily reusable for any resource type.
I used the code available here and here to create a custom one based on the requirements. Tested in my environment - it seems to work as expected.
I should disclose that I'm not an advanced PowerShell user, so the code I'm providing could really be sub-optimal.

Powershell script to get all parent resources

Good day,
I am trying to figure out a way to get all the parent objects in my azure subcription to a csv from Azure.
By parent object, I am refering to objects like, VMs, Webapps, Kubernetes Clusters, ect. I want to strip away any data that is deemed illrevelant like Nics, PIPs, storage disks, ect. I am not super proficent in powershell. and I am not sure how to tackle this.
I have an azure workbook that I created that gives a good overview in a nice format, I would like to export the entire workbook for offline viewing but that doesn't seem to be possible.
Any help would be greatly appreiciated.
So, what's an "interesting" resource to you may not be to the next person, and vice versa - in some cases, for example, I may set up NICs independently of my VMs, and want to see them. I don't think there's a way to automatically get just the things you want. What you could do is create a list of resources that are interesting to you (by type), and then use Powershell to create your report:
Get 'em all and filter 'em
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
Get-AzResource | ForEach-Object {
if ($resourceTypes -contains $_.resourceType) {
$resources += [PSCustomObject] #{
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
$resources | Sort-Object ResourceType, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Get 'em type by type (this one loops through subscriptions to which you have access, will print out a line with the current context on each subscription, will restore context to the current subscription when done)
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
$currentContext = Get-AzContext
try {
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$resourceTypes | ForEach-Object {
Get-AzResource -ResourceType $_ | ForEach-Object {
$resources += [PSCustomObject] #{
SubscriptionName = $subscriptionName
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
}
} finally {
$currentContext | Set-AzContext
}
$resources | Sort-Object ResourceType, SubscriptionName, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Whichever approach you choose, just customize the $resourceTypes list to contain just the resource types that you want.
To get a list of resource types, I do something like this:
Get-AzResourceProvider -ProviderNamespace Microsoft.Sql |
Select ProviderNamespace -Expand ResourceTypes |
Select #{ L="Provider"; E={ "$($_.ProviderNameSpace)/$($_.ResourceTypeName)" } }
Leave off the -ProviderNamespace Microsoft.Sql if you want to get all resource types, but that will be a long list.

How to get the list of azure servers having Auto-Shutdown disabled using PowerShell?

I want to get the list of azure servers having auto-shutdown disabled on them, I have the below script but the issue with the script is that it gets the list of RG's under the Subscription GUID but repeats the output after every loop.
Import-AzureRmContext -Path "$PSScriptRoot\AzureProfile.json"
Select-AzureRmSubscription -SubscriptionId {subscriptionId}
[array]$ResourceGroupArray = Get-AzureRMVm | Select-Object -Property ResourceGroupName, Name, VmId
foreach ($resourceGroup in $ResourceGroupArray){
$targetResourceId = (Get-AzureRmVM -ResourceGroupName $resourcegroup.ResourceGroupName -Name $resourceGroup.Name).Id
$shutdownInformation = (Get-AzureRmResource -ResourceGroupName $resourcegroup.ResourceGroupName -ResourceType Microsoft.DevTestLab/schedules -Expandproperties).Properties
Write-Host "ID: " $targetResourceId
$shutdownInformation
The output for each VM is displayed in the following format,
What I want is simple, I want the VM name and its status of Auto-shutdown to be displayed on the screen so that its easy for me to find out which all VM have auto-shutdown currently disabled on them.
Any help related to this would be helpful.
You just need to get the microsoft.devtestlab/schedules resource ID using:
/subscriptions/{subscriptionId}/resourceGroups/{rgName}/providers/microsoft.devtestlab/schedules/shutdown-computevm-{vmName}
Then iterate over all your VMs using Get-AzVM, Get the microsoft.devtestlab/schedules resource using Get-AzResource, then output VM name and status into a table using Format-Table.
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Set-AzContext -SubscriptionId $subscriptionId
& {
foreach ($vm in Get-AzVM) {
try {
$shutdownResource = Get-AzResource `
-ResourceId "/subscriptions/$subscriptionId/resourceGroups/$($vm.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($vm.Name)" `
-ErrorAction Stop
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $shutdownResource.Properties.status
}
}
catch {
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $_.Exception.Message
}
}
}
} | Format-Table -AutoSize
To set the context to the correct subscription, we can use Set-AzContext.
The above however is using the latest Az modules. You can do the same using the equivalent AzureRm modules.
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Set-AzureRmContext -SubscriptionId $subscriptionId
& {
foreach ($vm in Get-AzureRmVM) {
try {
$shutdownResource = Get-AzureRmResource `
-ResourceId "/subscriptions/$subscriptionId/resourceGroups/$($vm.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($vm.Name)" `
-ErrorAction Stop
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $shutdownResource.Properties.status
}
}
catch {
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $_.Exception.Message
}
}
}
} | Format-Table -AutoSize
Although I do recommend moving to the Az module since support for AzureRm is ending December 2020. You can read the documentation for more information about this.
The above code should give you an output similar to the following
VMName ShutdownStatus
------ --------------
vm1 Enabled
vm2 Disabled
Update
The Call operator & is used here to run the for loop as a script block. You can read more about this in about_Script_Blocks.
Try something like this to get the auto-shutdown status of all VMs. Instead of trying to get the schedules inside the loop, get all the ones in the subscription and match them based on the VM's full resource Id.
[array]$VMArray = Get-AzureRMVm | Select-Object -Property ResourceGroupName, Name, VmId, Id
$ShutdownInformation = (Get-AzureRmResource -ResourceType Microsoft.DevTestLab/schedules -Expandproperties).Properties
foreach($vm in $VMArray) {
$ShutdownStatus = "Not Configured"
$Schedule = $ShutdownInformation | Where-Object { $_.targetResourceId -eq $vm.Id } | Select -First 1
if($Schedule -ne $null) {
$ShutdownStatus = $Schedule.status
}
Write-Host $vm.VmId $ShutdownStatus
}

Azure PS query to obtain resource providers registered specific to a given resource group

Get-AzureRmResourceProvider -ListAvailable | Select-Object ProviderNamespace, RegistrationState
The above PS query can get me all the resource providers and registered state.
Now, when I have resource-group with a few resources added
Is it possible to script a PS/Cloud Shell query to get the resource providers needed for just the resources in that specific resource group ?
just do a Get-AzResource and find all the resource types in that resource group, something like:
Get-AzResource -ResourceGroupName xxx | Select-Object ResourceType
if you want unique types just use the below :
Get-AzResource -ResourceGroupName xxx | Select-Object Resource Type -Unique
Try the command below, the $arrayList is all the resource providers of the resource group.
$a = (Get-AzureRmResource -ResourceGroupName joywebapp).ResourceType
$arrayList = New-Object System.Collections.ArrayList
foreach($item in $a){
if($arrayList.Contains(($item -split("/"))[0]) -eq $false){
$arrayList.Add((($item -split("/"))[0])) | Out-Null
}
}

Resources