Trying to list Azure Virtual Network and export to CSV using Powershell - azure

I am trying to create a script that can list all the Azure virtual networks and export it into Csv using Powershell.
$day = Get-Date -Format " MMM-yyyy"
$path = "C:\Users\admin-vishal.singh\Desktop\Test\Report\"+ "$day-Vnet-Report.csv"
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
$resource_grps = Get-AzResourceGroup
foreach ($resource_grp in $resource_grps) {
$networks = Get-AzVirtualNetwork
foreach ($vnet in $networks)
{
$null = Get-AzVirtualNetwork |Select-Object SubscriptionName,ResourceGroupName,Name,AddressSpace,Subnets,SubnetAddressSpace,RouteTable | Export-CSV -Path $path -NoTypeInformation -Encoding ASCII -Append
}
}
}
I am not able to retrieve data in the right format & getting errors when retrieving data.
Below is snippet of data
Lots of values I am not able to retrieve like Subnet AddressSpace, Route Tables and Routes.

Building on what Jim Xu provided, you don't need to have a separate loop for each ResourceGroup. Get-AzVirtualNetwork will return all virtual networks for the entire subscription. Also, you'll need an expression for the SubscriptionName in the Select-Object, so the code would look like this:
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
Get-AzVirtualNetwork |
Select-Object `
#{label='SubscriptionName'; expression={$Sub.Name}}, `
ResourceGroupName, `
Name, `
#{label='AddressSpace'; expression={$_.AddressSpace.AddressPrefixes}}, `
#{label='SubnetName'; expression={$_.Subnets.Name}}, `
#{label='SubnetAddressSpace'; expression={$_.Subnets.AddressPrefix}} |
Export-CSV -Path $path -NoTypeInformation -Encoding ASCII -Append
}

When we call export-csv command, the property values are converted to strings using the ToString() method. But the result of Get-AzVirtualNetwork are object, we cannot directly convert the value to string. For more details, please refer to here and here
So regarding the issue, I suggest you create a custom object with the information you need then save it into csv.
For exmaple
$vents =Get-AzVirtualNetwork|
Select-Object SubscriptionName,ResourceGroupName,Name, #{
label='AddressSpace'
expression={$_.AddressSpace.AddressPrefix}}, #{
label='SubnetName'
expression={$_.Subnets.Name}
}, #{
label='SubnetAddressSpace'
expression={$_.Subnets.AddressPrefix}
}
$vents | convertto-csv

Related

Update Azure tags of resources

I am pretty new to powershell and please bear with me. I am building a script wherein I need to replace one of the key value pairs of a Tag of any resources in a certain subscription. It can be the "Name" or "Value" of a Tag.
I got a script that will find and old Tag key and replace it with a new Tag key. It checks all resources and locate the old tag and replace it with a new tag successfully. Now, my dilemma is it only do the job for the "Name" part of Tag but not with the "Value" of the tag. Can anyone help me on how to do the "Value" part of the Tag, please.
Over all, the code will search for a tag from $oldKey across all the resources and replace it with $newKey. It does create a report of what resources it made changes and put it to a csv file.
#Define old Tag key $oldkey and new Tag key $newKey
$oldKey = "camp"
$newKey = "Camp3"
#Find ResourceGroups with oldKey, backup findings to CSV, migrate existing oldKey value to newKey merging with existing tags, then delete oldKey.
$rgsOldKeyBackup = Get-AzResourceGroup | Where-Object {$_.Tags.Keys -match $oldKey}
$rgsOldKeyBackup.count
if ($rgsOldKeyBackup) {
Get-AzResourceGroup | Where-Object {$_.Tags.Keys -match $oldKey} | Out-File "C:\temp\AzRGs-Tag-Backup-$oldkey.csv"
$rgs = Get-AzResourceGroup | Where-Object {$_.Tags.Keys -match $oldKey}
$rgs | ForEach-Object {
$rgOldKeyValue = $_.Tags.$oldKey
$rgNewTag = #{$newKey=$rgOldKeyValue}
$rgOldTag = #{$oldKey=$rgOldKeyValue}
$resourceID = $_.ResourceId
Update-AzTag -ResourceId $resourceID -Tag $rgNewTag -Operation Merge
$Check = Get-AzResourceGroup -Id $resourceID | Where-Object {$_.Tags.Keys -match $newKey}
if ($Check) {
Update-AzTag -ResourceId $resourceID -Tag $rgOldTag -Operation Delete
}
}
}
#Find Resources with oldKey, backup findings to CSV, migrate existing oldKey value to newKey merging with existing tags, then delete oldKey.
$resourcesOldKeyBackup = Get-AzResource | Where-Object {$_.Tags.Keys -match $oldKey}
$resourcesOldKeyBackup.count
if ($resourcesOldKeyBackup) {
Get-AzResource | Where-Object {$_.Tags.Keys -match $oldKey} | Out-File "C:\temp\AzResources-Tag-Backup-$oldkey.csv"
$resources = Get-AzResource | Where-Object {$_.Tags.Keys -match $oldKey}
$resources | ForEach-Object {
$resourcesOldKeyValue = $_.Tags.$oldKey
$resourcesNewTag = #{$newKey=$resourcesOldKeyValue}
$resourcesOldTag = #{$oldKey=$resourcesOldKeyValue}
$resourceID = $_.ResourceId
Update-AzTag -ResourceId $resourceID -Tag $resourcesNewTag -Operation Merge
$Check = Get-AzResource -ResourceId $resourceID | Where-Object {$_.Tags.Keys -match $newKey}
if ($Check) {
Update-AzTag -ResourceId $resourceID -Tag $resourcesOldTag -Operation Delete
}
}
}
Also, I would appreciate if you can help as well to make it more interactive and will ask to input an old key I am looking for and what will be the replacement instead of hardcoding the values in the script itself.
I Tried to reproduce the same in my environment to replace the Azure Tags using Powershell:
PowerShell Script:
connect-azaccount
$oldTagKey = "OldTagKey"
$oldTagValue = "OldTagValue"
$replacedTags= #{"NewTagKey"="NewTagValue"}
#$resourcelist= Get-AzResource
$resources = Get-AzResourceGroup | Where-Object {$_.Tags.Keys -match "OldTagKey"}
foreach($item in $resources){
# Get the current tags for the resource
$tags = $item.Tags
if ($tags.ContainsKey($oldTagKey)) {
# Update the tag with the new tag key and value
$tags[$newTagKey] = $newTagValue
# Remove the old tag
$tags.Remove($oldTagKey)
Update-Aztag -ResourceId $item.ResourceId -Tag $replacedTags -Operation Replace
}
}
Azure Tag Name and Value both are updated with new values.
Once ran the above commands Tags are updated in Resource Group.
Refer MS Doc more about Azure Tags using Powershell.
to search for resource groups with tag name or value equals to xxx:
$searchPattern = 'xxx'
$resourceGroups = Search-AzGraph "ResourceContainers | where tags contains '$searchPattern' and type =~ 'microsoft.resources/subscriptions/resourcegroups'"
and then you just have to iterate over the result pretty much the same way you do. main advantage over your code - this scans all available subscriptions and does filtering on Azure side, so a lot quicker.

PowerShell: Output provider results from multiple Azure subscriptions into one .txt file - via arrayList

I am trying to get the registered providers for multiple subscriptions and output everything into one file.
For that, i am getting the subscriptions from a folder full of *.yaml files that contain information about the subscriptions, including their name.
What i cannot achieve is get the result for each subscriptions into an array and output that array into a text file. The script also allows the use of only one item from the folder in case that is the case.
Here is a sample code of a subscription and the code for it:
subscription1.yaml
name: subscription1
emailContact: email.address#domain.com
tags:
- key: "key1"
value: "Value1"
subscription2.yaml
name: subscription2
emailContact: email.address#domain.com
tags:
- key: "key1"
value: "Value1"
Folder structure where the yaml files is: ./landingZones/landingzone1/settings/dev/*.yaml
script:
param (
[Parameter(Mandatory = $false)]
[string]$Environment = 'dev',
[Parameter(Mandatory = $false)]
[string]$LandingZoneType = 'landingzone1',
[Parameter(Mandatory = $false)]
[string]$SingleSubscription
)
$scriptPath = Split-Path -parent $PSCommandPath
$subscriptionsEnvironmentDirectory = Get-ChildItem -Directory $scriptPath -Recurse -Filter "*$Environment*" | Where-Object { $_.parent.parent.Name -eq $LandingZoneType }
$subscriptions = Get-ChildItem -Path $($subscriptionsEnvironmentDirectory.FullName)
foreach ($subscription in ($subscriptions | Where-Object { ([System.String]::IsNullOrEmpty($SingleSubscription)) -or ($_.Name -replace "\.[^\.]+$", '') -eq $SingleSubscription })) {
$landingZone = Get-Content -Path $subscription.FullName | ConvertFrom-Yaml
# Set subscriptionName variable
$subscriptionName = $landingZone.name
$providers = az provider list --subscription $subscriptionName | ConvertFrom-Json
$defaultRegisteredProviders = 'Microsoft.ADHybridHealthService|Microsoft.Authorization|Microsoft.Billing|Microsoft.ClassicSubscription|Microsoft.Commerce|Microsoft.Consumption|Microsoft.CostManagement|Microsoft.Features|Microsoft.MarketplaceOrdering'
$registeredProviders = $providers | Where-Object { ($_.registrationState -eq 'Registered') -and ($_.namespace -notmatch $defaultRegisteredProviders) }
# Outputting result into txt file in the same directory where the command was executed
Write-Host ('{1}# Registered providers for subscription [{0}]' -f $subscriptionName, "`n")
$list = New-Object -TypeName 'System.Collections.ArrayList'
$sortedObjects = $registeredProviders | Sort-Object namespace | `
Format-Table `
#{l = 'Namespace'; e = { $_.namespace } }, `
#{l = "Subscription Id [$subscriptionName]"; e = { $_.id } }, `
#{l = 'Registration State'; e = { $_.registrationState } }, `
#{l = 'Registration Policy'; e = { $_.registrationPolicy } }
foreach ($i in $sortedObjects) {
$list.Add($i) | Out-Null
}
# Alternative to add into array:
# #($sortedObjects).foreach({$list.Add($_)}) | Out-Null
}
$list.Count
$list | Out-File .\registered_providers.txt -Force
The result is a file called 'registered_providers.txt' that contains only the registered providers for the first subscription in the foreach loop. I cannot get the contents of the second, third and so on in the same file, just a replaced text from the $sortedObjects
How do i create the array to contain all the info from all the subscriptions called?
Thanks
$list | Out-File Should be inside the for loop so that all the data you are fetching will be stored in the specified file.
Out-File cmdlet has -append parameter that appends the output to the existing file for every for loop happens. Otherwise, it will clean up the information/value stored in that output file.
Thanks to #jdweng for pointing the user to the right solution.
Refer to this MS Doc on Out-File -Append Parameter usage.

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.

In Azure, To get Load balancer details in to csv file using powershell script

I wrote a powershell script in Azure DevOps pipeline to get Load Balancer details like FrontendIPConfigurationsName,FrontendIPAddress in to csv file. AM getting those details but FrontendIPConfigurationsNames which starts with same name like "ers-A1,ers-B1,ers-C1,ers-D1" are coming in same row. But I want to get them in different rows.Please suggest
$excel = #()
LBlist = Get-AZLoadBalancer | Where-Oject {$_.ResourceGroupName -clike '$(grp-wildcard)'} | Select-Object
foreach ($LB in LBlist)
$Array =""| Select-Object ResourceGroupName, FrontendIPConfigurationsName,FrontendIPAddress
$Array.ResourceGroupName =$LB.ResourcegroupName
$Array.FrontendIPConfigurationsName = ($LB.FrontendIpConfigurationsName.name -join ',')
$Array.FrontendIPAddress =($LB.FrontendIpConfigurations.PrivateIpAddress -join ',')
}
$excel +=$Array
$excel |Format-Table ResourceGroupName, FrontendIPConfigurationsName,FrontendIPAddress
$excel | Export-Csv -NTI -Path "($Build.ArtifactStagingDirectory)/LBlist.csv
You can do something similar to this to get the objects on separate rows.
$LBlist = Get-AZLoadBalancer | Where-Object { $_.ResourceGroupName -clike '$(grp-wildcard)' }
$LBlist | Export-Csv -NTI -Path "$(Build.ArtifactStagingDirectory)/LBlist.csv"
Mock for Get-AZLoadBalancer (not sure if it's entirely accurate as I've never used Az Powershell)
function Get-AZLoadBalancer() {
$obj = #(
[PSCustomObject] #{
ResourceGroupName = '$(grp-wildcard)'
FrontendIPConfigurationsName = 'ers-A1'
FrontEndIPAddress = '1.2.3.4'
},
[PSCustomObject] #{
ResourceGroupName = '$(grp-wildcard)'
FrontendIPConfigurationsName = 'ers-B1'
FrontEndIPAddress = '1.2.3.5'
}
)
return $obj
}

How to output Azure Virtual Network Subnets to csv using powershell for single or multiple subscriptions

I am new to powershell and trying to output subnet information for Azure Virtual Networks in either single or multiple subscriptions.
I can output to the console and get the results I'm looking for but struggling to get the same output to a csv file.
I understand that I need to create New Objects, etc. but can't get the correct syntax to work.
Could anyone help please.
Working code below....
$subs = Get-AzSubscription -SubscriptionID xxxxxxxxxxxxxxxx
foreach ($Sub in $Subs) {
$SelectSub = Select-AzSubscription -SubscriptionName $Sub.Name
$VNETs = Get-AzVirtualNetwork
foreach ($VNET in $VNETs) {
$Sub.Name
$VNET.Name
($VNET).AddressSpace.AddressPrefixes
($VNET).Subnets.Name
Write-Host " "
}
}
I think something like this will do the trick:
$subs = Get-AzSubscription -SubscriptionID xxxxxxxxxxxxxxxx
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
$networks = Get-AzVirtualNetwork | ForEach-Object {
New-Object PSObject -Property #{
name = $_.name
subnets = $_.subnets.name -join ';'
addressSpace = $_.AddressSpace.AddressPrefixes -join ';'
}
}
$networks | Export-Csv -NoTypeInformation file.csv
}
edit: previous version didnt really work, export-csv is a bit weird, i guess.

Resources