Achraf Ben Alaya
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
SUBSCRIBE
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog Cloud Azure

PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis

achraf by achraf
November 2, 2024
in Azure, Blog, Cloud
3 min read
0
PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis
0
SHARES
688
VIEWS
Share on FacebookShare on Twitter

For an inventory for our company, which has over 100 subscriptions and thousands of virtual machines and resources, my colleague recently asked me if it is possible to obtain comprehensive data regarding Virtual Networks (VNets) and their subnets across all Azure subscriptions with their Nic name attached, the service endpoints, and the total available IP. We needed to share this information with the Netowkr team for some feature enhancements. I wrote the code below for some internal studies, which generates crucial data including IP settings, address prefixes, and connected devices. A CSV file with the results is saved.

How to Use :


1 – Connect to Azure: Run Connect-AzAccount to authenticate and connect to your Azure account.
2 – Execute the Script: Copy and run the script in your PowerShell environment.
3 – View Results: The script outputs a summary to the console and saves detailed results to a specified CSV file.
4 – Access the CSV: Open the CSV file located at path.csv` to review the details.

This script is useful for administrators needing to audit network configurations and IP usage across multiple Azure subscriptions.

#Connect-AzAccount
# Define the subscription name
$subs = Get-AzSubscription 
# Initialize an array to store the results
$results = @()
# Initialize location  to store the results
$csvFilePath = "insert your path here\data.csv"
foreach ($Sub in $subs) {
    Write-Host "***************************"
    Write-Host " "
    Write-Host "Subscription: $Sub"
    Write-Host " "
    Write-Host "***************************"
    Write-Host " "
    $Sub.Name 
    
    $SelectSub = Select-AzSubscription -SubscriptionName $Sub.Name


    # Get all virtual networks in the subscription
    $VNETs = Get-AzVirtualNetwork
    foreach ($VNET in $VNETs) {
        Write-Host "--------------------------"
        Write-Host " "
        Write-Host "   vNet: $($VNET.Name)"
        Write-Host "   AddressPrefixes: $($VNET.AddressSpace.AddressPrefixes -join ', ')"
        Write-Host " "

        # Get expanded virtual network details including subnets and IP configurations
        $vNetExpanded = Get-AzVirtualNetwork -Name $VNET.Name -ResourceGroupName $VNET.ResourceGroupName -ExpandResource 'subnets/ipConfigurations'

        foreach ($subnet in $vNetExpanded.Subnets) {
            Write-Host "       Subnet: $($subnet.Name)"
            $connectedDevices = $subnet.IpConfigurations.Count
            Write-Host "          Connected devices: $connectedDevices"

            # Calculate total, used, and available IPs in the subnet
            $subnetMask = $subnet.AddressPrefix.Split('/')[1]
            $totalIps = [math]::Pow(2, 32 - $subnetMask)
            $reservedIps = 5  # 5 IPs are reserved by Azure
            $usedIps = $connectedDevices + $reservedIps
            $availableIps = $totalIps - $usedIps
            Write-Host "          Total IPs: $totalIps"
            Write-Host "          Used IPs: $usedIps"
            Write-Host "          Available IPs: $availableIps"

            # Get activated Service Endpoints
            $serviceEndpoints = if ($subnet.ServiceEndpoints) { $subnet.ServiceEndpoints.Service -join ', ' } else { "None" }
            Write-Host "          Service Endpoints: $serviceEndpoints"

            # Get Delegations Service Names
            $delegations = if ($subnet.Delegations) { $subnet.Delegations.ServiceName -join ', ' } else { "None" }
            Write-Host "          Delegations: $delegations"

            # Join the address prefixes into a single string
            $addressPrefixString = $subnet.AddressPrefix -join ', '

            # Add information for each IP configuration in the subnet
            foreach ($ipConfig in $subnet.IpConfigurations) {
                Write-Host "            IP Address: $($ipConfig.PrivateIpAddress)"

                # Attempt to get the VM name associated with this IP configuration
                $nic = Get-AzNetworkInterface | Where-Object { $_.IpConfigurations.Id -eq $ipConfig.Id }
                if ($nic) {
                    $vm = Get-AzVM | Where-Object { $_.Id -eq $nic.VirtualMachine.Id }
                    $vmName = if ($vm) { $vm.Name } else { "Not Available" }

                    # Add the information to the results array
                    $results += [PSCustomObject]@{
                        Subscription      = $Sub
                        VNet              = $VNET.Name
                        Subnet            = $subnet.Name
                        AddressPrefix     = $addressPrefixString
                        TotalIps          = $totalIps
                        UsedIps           = $usedIps
                        AvailableIps      = $availableIps
                        ConnectedDevices  = $connectedDevices
                        ServiceEndpoints  = $serviceEndpoints
                        Delegations       = $delegations
                        IpAddress         = $ipConfig.PrivateIpAddress
                        VMName            = $vmName
                        NicName           = $nic.Name
                    }
                } else {
                    # Add the information to the results array
                    $results += [PSCustomObject]@{
                        Subscription      = $Sub
                        VNet              = $VNET.Name
                        Subnet            = $subnet.Name
                        AddressPrefix     = $addressPrefixString
                        TotalIps          = $totalIps
                        UsedIps           = $usedIps
                        AvailableIps      = $availableIps
                        ConnectedDevices  = $connectedDevices
                        ServiceEndpoints  = $serviceEndpoints
                        Delegations       = $delegations
                        IpAddress         = $ipConfig.PrivateIpAddress
                        VMName            = "Not Available"
                        NicName           = "Not Available"
                    }
                }
            }

            # If there are no IP configurations, add a record with "0" connected devices
            if ($connectedDevices -eq 0) {
                $results += [PSCustomObject]@{
                    Subscription      = $Sub
                    VNet              = $VNET.Name
                    Subnet            = $subnet.Name
                    AddressPrefix     = $addressPrefixString
                    TotalIps          = $totalIps
                    UsedIps           = $usedIps
                    AvailableIps      = $availableIps
                    ConnectedDevices  = 0
                    ServiceEndpoints  = $serviceEndpoints
                    Delegations       = $delegations
                    IpAddress         = ""
                    VMName            = ""
                    NicName           = ""
                }
            }

            Write-Host " "
        }
    }
    Write-Host "***************************"
}

# Display the results in a table format
$results | Format-Table -AutoSize

# Export the results to a CSV file

$results | Export-Csv -Path $csvFilePath -NoTypeInformation

# Output a message to indicate the script has finished
Write-Output "Script completed. Results have been saved to CSV files."

# Open the CSV file to show the results
Invoke-Item -Path $csvFilePath

Results (Fake Data Results ,as i can not share real data ^^' )

Source Code  : link 

ShareTweet
Previous Post

Automated Monitoring of Azure App Registration Secrets with Automation Accounts and Logic Apps

Next Post

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

Related Posts

Azure

Honored to be recognized as a Microsoft Azure MVP for 2025-2026

July 20, 2025
90
AI

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025
242
Azure

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025
701
Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet
Azure

Network Security & Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet

February 3, 2025
185
Understanding Generative AI and RAG Benefits
AI

Understanding Generative AI and RAG Benefits

January 12, 2025
138
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring
Azure

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

December 8, 2024
2.2k
Next Post
Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

Azure Communication Services Email Sending Simplified: From Setup to Execution and Monitoring

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

Migrate and modernize your applications on Azure

Migrate and modernize your applications on Azure – Part 2.0 (Azure Functions)

April 3, 2021
560
How to SSH into AKS Nodes

How to SSH into AKS Nodes

May 11, 2021
7.7k
Installing WordPress with docker image of XAMPP

Installing WordPress with docker image of XAMPP

April 21, 2020
1.2k
Reflecting on My Journey as a Microsoft MVP in 2024

Reflecting on My Journey as a Microsoft MVP in 2024

March 24, 2024
379
Goodbye my lover Xamarin, Hello MAUI!

Goodbye my lover Xamarin, Hello MAUI!

September 25, 2020
606
Elevate Your API Reliability: Deep Dive into Load Balancing and Failover Strategies in Azure API Management

Elevate Your API Reliability: Deep Dive into Load Balancing and Failover Strategies in Azure API Management

December 29, 2023
402
Facebook Twitter LinkedIn Youtube

Honored to be recognized as a Microsoft Azure MVP for 2025-2026

July 20, 2025

Model Context Protocol (MCP): The Future of AI Integration

April 21, 2025

Step-by-Step Guide: Azure Front Door + Storage Account Static Website + Custom Domain with Terraform

March 11, 2025

Categories

  • AI (2)
  • Apps (1)
  • Azure (64)
  • blazor (2)
  • Blog (91)
  • c# (7)
  • Cloud (66)
  • Courses (4)
  • Dapr (4)
  • docker (4)
  • Games (1)
  • General Tips & Fix (1)
  • Home (1)
  • Kubernetes Service (AKS) (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Terrafrom (1)
  • Tricks, Tips and Fixes (4)
  • xamarin (5)
No Result
View All Result
  • Home
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
    • General Tips & Fix
  • AI
  • Cloud
  • Motivation
  • Courses
  • About
    • Resume
    • Privacy Policy