<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>powershell &#8211; achraf ben alaya</title>
	<atom:link href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/tag/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net</link>
	<description>Tech Blog By Achraf Ben Alaya</description>
	<lastBuildDate>Mon, 03 Feb 2025 08:28:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.7</generator>

<image>
	<url>/wp-content/uploads/2022/02/cropped-me-scaled-1-32x32.jpeg</url>
	<title>powershell &#8211; achraf ben alaya</title>
	<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">189072172</site>	<item>
		<title>Network Security &#038; Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2025/02/01/network-security-route-tables-checking-nsgs-route-tables-and-service-endpoints-for-a-targeted-vnet-or-subnet/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=network-security-route-tables-checking-nsgs-route-tables-and-service-endpoints-for-a-targeted-vnet-or-subnet</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2025/02/01/network-security-route-tables-checking-nsgs-route-tables-and-service-endpoints-for-a-targeted-vnet-or-subnet/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sat, 01 Feb 2025 13:04:38 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[azure]]></category>
		<category><![CDATA[powershell]]></category>
		<category><![CDATA[subnet]]></category>
		<category><![CDATA[vnet]]></category>
		<guid isPermaLink="false">https://achrafbenalaya.com/?p=2114</guid>

					<description><![CDATA[For an inventory for our company related to remediation (anything that was deployed before using the portal we import it via terraform and later apply our standards too) we have been asked to get details about each virtual network and subnet and the connected ressources to those vnet ,why ? because sometimes we will need [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>For an inventory for our company related to remediation (anything that was deployed before using the portal we import it via terraform and later apply our standards too) we have been asked to get details about each virtual network and subnet and the connected ressources to those vnet ,why ? because sometimes we will need to add some routes in our udr , sometimes we update the nsgs and some other times if we found out a vnet is a legacy we see if we are going to delete it .<br><br>In an earlier blog post we have written : PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis we have extracted everything related to all the vent in our </p>


<a class="wp-block-read-more" href="https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2025/02/01/network-security-route-tables-checking-nsgs-route-tables-and-service-endpoints-for-a-targeted-vnet-or-subnet/" target="_self">https://achrafbenalaya.com/2024/11/02/powershell-automation-for-azure-networks-detailed-vnet-and-subnet-analysis/<span class="screen-reader-text">: Network Security &amp; Route Tables – Checking NSGs, route tables, and service endpoints for a targeted VNET or Subnet</span></a>


<p class="has-text-align-left">subscriptions (over 100 sub) for that my college asked me if it is possible to write another script only to target one vnet or one subnet in a vnet ,and that&#8217;s normal since he does not need details about all the vnet&#8217;s that exist , and he need an updated version of the report since any change can happen and he can no be based on an older report .<br><br>for that I have added this two scripts below to help extract details about the vnet and subent and save the report in a stylish table format in excel .<br><br></p>



<h2 class="wp-block-heading">How to Use :</h2>



<p>1 – Connect to Azure: Run Connect-AzAccount to authenticate and connect to your Azure account.<br>2- Install-Module -Name ImportExcel -Scope CurrentUser -Force<br>3- Insert the subscription id ,the ressource group name ,the vnet ,and the subnet is optionel.<br>4 – Execute the Script: Copy and run the script in your PowerShell environment.<br>5 – View Results: The script outputs a summary to the console and saves detailed results to a specified Excel file.<br>6 – Access the Excel : Open the XlSX file located at path.xlxs` to review the details.</p>



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



<p>Script:<br><br></p>



<pre class="wp-block-code"><code>$subscriptionId = ''
$resourceGroupName = ''
$vnetName = ''
$subnetName = ''  # Can be empty to process all subnets
$desktopPath = &#91;System.Environment]::GetFolderPath("Desktop")
$exportDirectory = "$desktopPath\export_subnets"

Import-Module ImportExcel -Force

# Connect to Azure
Select-AzSubscription -SubscriptionId $subscriptionId

# Get the virtual network
$vnet = Get-AzVirtualNetwork -Name $vnetName -ResourceGroupName $resourceGroupName
if (-not $vnet) {
    Write-Host "The VNet $vnetName was not found." -ForegroundColor Red
    exit
}

# Function to process a single subnet
function Process-Subnet {
    param (
        &#91;Parameter(Mandatory=$true)]
        $subnet
    )

    Write-Host "--------------------------"
    Write-Host " "
    Write-Host "   Subnet: $($subnet.Name)"
    $connectedDevices = $subnet.IpConfigurations.Count
    Write-Host "   Connected devices: $connectedDevices"

    # Calculate IPs
    $subnetMask = $subnet.AddressPrefix.Split('/')&#91;1]
    $totalIps = &#91;math]::Pow(2, 32 - $subnetMask)
    $reservedIps = 5
    $usedIps = $connectedDevices + $reservedIps
    $availableIps = $totalIps - $usedIps
    Write-Host "   Total IPs: $totalIps"
    Write-Host "   Used IPs: $usedIps"
    Write-Host "   Available IPs: $availableIps"

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

    # Subnet address
    $addressPrefixString = $subnet.AddressPrefix -join ', '

    # Network interfaces
    $networkInterfaces = Get-AzNetworkInterface | Where-Object { $_.IpConfigurations.Subnet.Id -eq $subnet.Id }
    $results = @()

    foreach ($nic in $networkInterfaces) {
        foreach ($ipConfig in $nic.IpConfigurations) {
            $vm = Get-AzVM | Where-Object { $_.Id -eq $nic.VirtualMachine.Id }
            $vmName = if ($vm) { $vm.Name } else { "Not Available" }

            $results += &#91;PSCustomObject]@{
                Subscription     = &#91;string]$subscriptionId
                VNet            = &#91;string]$vnetName
                Subnet          = &#91;string]$subnet.Name
                AddressPrefix   = &#91;string]$addressPrefixString
                TotalIps        = &#91;int64]$totalIps
                UsedIps         = &#91;int64]$usedIps
                AvailableIps    = &#91;int64]$availableIps
                ConnectedDevices= &#91;int]$connectedDevices
                ServiceEndpoints= &#91;string]$serviceEndpoints
                Delegations     = &#91;string]$delegations
                IpAddress       = &#91;string]$ipConfig.PrivateIpAddress
                VMName          = &#91;string]$vmName
                NicName         = &#91;string]$nic.Name
                AttachedTo      = &#91;string]"NIC: $($nic.Name), VM: $vmName"
            }
        }
    }

    # If no device found, add an empty row
    if ($results.Count -eq 0) {
        $results += &#91;PSCustomObject]@{
            Subscription     = &#91;string]$subscriptionId
            VNet            = &#91;string]$vnetName
            Subnet          = &#91;string]$subnet.Name
            AddressPrefix   = &#91;string]$addressPrefixString
            TotalIPs        = &#91;int64]$totalIps
            UsedIPs         = &#91;int64]$usedIps
            AvailableIPs    = &#91;int64]$availableIps
            ConnectedDevices= &#91;int]0
            ServiceEndpoints= &#91;string]$serviceEndpoints
            Delegations     = &#91;string]$delegations
            IpAddress       = &#91;string]""
            VMName          = &#91;string]""
            NicName         = &#91;string]""
            AttachedTo      = &#91;string]"Not Applicable"
        }
    }

    return $results
}

# Determine which subnets to process
$subnetsToProcess = @()
if (&#91;string]::IsNullOrEmpty($subnetName)) {
    $subnetsToProcess = $vnet.Subnets
    $exportFileName = "all_subnets.xlsx"
} else {
    $subnet = $vnet.Subnets | Where-Object { $_.Name -eq $subnetName }
    if (-not $subnet) {
        Write-Host "The subnet $subnetName was not found." -ForegroundColor Red
        exit
    }
    $subnetsToProcess = @($subnet)
    $exportFileName = "$subnetName.xlsx"
}

# Process all selected subnets
$allResults = @()
foreach ($subnet in $subnetsToProcess) {
    $results = Process-Subnet -subnet $subnet
    $allResults += $results
}

# Create export directory if it doesn't exist
if (-not (Test-Path -Path $exportDirectory)) {
    Write-Host "Creating export directory: $exportDirectory"
    New-Item -ItemType Directory -Path $exportDirectory | Out-Null
}

$excelFilePath = "$exportDirectory\$exportFileName"

try {
    $excelApp = New-Object -ComObject Excel.Application
    $excelApp.Visible = $false

    $workbook = $excelApp.Workbooks.Add()
    $worksheet = $workbook.Sheets.Item(1)
    $worksheet.Name = "Subnet Report"

    # Define headers with formatting
    $headers = @("Subscription", "VNet", "Subnet", "AddressPrefix", "TotalIPs", "UsedIPs", "AvailableIPs", 
                "ConnectedDevices", "ServiceEndpoints", "Delegations", "IpAddress", "VMName", "NicName", "AttachedTo")

    for ($i = 0; $i -lt $headers.Count; $i++) {
        $cell = $worksheet.Cells.Item(1, $i + 1)
        $cell.Value = $headers&#91;$i]
        $cell.Font.Bold = $true
        $cell.Interior.ColorIndex = 37
        $cell.Borders.LineStyle = 1
    }

    # Insert data with borders
    $row = 2
    foreach ($result in $allResults) {
        for ($col = 1; $col -le $headers.Count; $col++) {
            $cell = $worksheet.Cells.Item($row, $col)
            $propertyName = $headers&#91;$col - 1]
            $propertyValue = $result.$propertyName
            
            # Convert numeric values to strings for Excel
            if ($propertyValue -is &#91;int64] -or $propertyValue -is &#91;int] -or $propertyValue -is &#91;double]) {
                $cell.Value2 = &#91;double]$propertyValue
            } else {
                $cell.Value2 = &#91;string]$propertyValue
            }
            
            $cell.Borders.LineStyle = 1
        }
        $row++
    }

    # Auto-fit column widths
    $worksheet.Columns.AutoFit()

    # Save and close the Excel file
    $workbook.SaveAs($excelFilePath)
    $workbook.Close()
    $excelApp.Quit()

    Write-Host "&#x2705; Export completed! File saved at: $excelFilePath" -ForegroundColor Green
    Invoke-Item -Path $excelFilePath
} catch {
    Write-Host "&#x274c; An error occurred: $($_.Exception.Message)" -ForegroundColor Red
} finally {
    if ($excelApp) { &#91;System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelApp) }
}</code></pre>



<figure class="wp-block-gallery has-nested-images columns-default is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex">
<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="2229" height="835" data-id="2127" src="/wp-content/uploads/2025/02/Sans-titre-3.png" alt="" class="wp-image-2127" srcset="/wp-content/uploads/2025/02/Sans-titre-3.png 2229w, /wp-content/uploads/2025/02/Sans-titre-3-300x112.png 300w, /wp-content/uploads/2025/02/Sans-titre-3-1024x384.png 1024w, /wp-content/uploads/2025/02/Sans-titre-3-768x288.png 768w, /wp-content/uploads/2025/02/Sans-titre-3-1536x575.png 1536w, /wp-content/uploads/2025/02/Sans-titre-3-2048x767.png 2048w, /wp-content/uploads/2025/02/Sans-titre-3-750x281.png 750w, /wp-content/uploads/2025/02/Sans-titre-3-1140x427.png 1140w" sizes="(max-width: 2229px) 100vw, 2229px" /></figure>
</figure>



<p class="has-vivid-cyan-blue-color has-text-color has-link-color wp-elements-6c20d23f8fc4e25fb4a61a70d6578137">Ps : This article was written in collaboration with my friend Malik .</p>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2025/02/01/network-security-route-tables-checking-nsgs-route-tables-and-service-endpoints-for-a-targeted-vnet-or-subnet/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2114</post-id>	</item>
		<item>
		<title>PowerShell Automation for Azure Networks: Detailed VNET and Subnet Analysis</title>
		<link>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2024/11/02/powershell-automation-for-azure-networks-detailed-vnet-and-subnet-analysis/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-automation-for-azure-networks-detailed-vnet-and-subnet-analysis</link>
					<comments>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2024/11/02/powershell-automation-for-azure-networks-detailed-vnet-and-subnet-analysis/#respond</comments>
		
		<dc:creator><![CDATA[achraf]]></dc:creator>
		<pubDate>Sat, 02 Nov 2024 15:04:37 +0000</pubDate>
				<category><![CDATA[Azure]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Cloud]]></category>
		<category><![CDATA[powershell]]></category>
		<guid isPermaLink="false">https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/?p=2011</guid>

					<description><![CDATA[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. [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>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.<br /><br /></p>
<h4>How to Use :</h4>
<p><br />1 &#8211; Connect to Azure: Run Connect-AzAccount to authenticate and connect to your Azure account.<br />2 &#8211; Execute the Script: Copy and run the script in your PowerShell environment.<br />3 &#8211; View Results: The script outputs a summary to the console and saves detailed results to a specified CSV file.<br />4 &#8211; Access the CSV: Open the CSV file located at path.csv` to review the details.</p>
<p>This script is useful for administrators needing to audit network configurations and IP usage across multiple Azure subscriptions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="powershell">#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
</pre>
<pre class="wp-block-code"><br />Results (Fake Data Results ,as i can not share real data ^^' )<br /><br /></pre>
<p>Source Code  : <a href="https://github.com/achrafbenalaya/achrafbenalaya.com">link </a></p>





<figure class="wp-block-image size-large"><a href="/wp-content/uploads/2024/11/Sans-titre-1.png"><img decoding="async" class="aligncenter size-full wp-image-2017" src="/wp-content/uploads/2024/11/Sans-titre-1.png" alt="" width="2513" height="932" srcset="/wp-content/uploads/2024/11/Sans-titre-1.png 2513w, /wp-content/uploads/2024/11/Sans-titre-1-300x111.png 300w, /wp-content/uploads/2024/11/Sans-titre-1-1024x380.png 1024w, /wp-content/uploads/2024/11/Sans-titre-1-768x285.png 768w, /wp-content/uploads/2024/11/Sans-titre-1-1536x570.png 1536w, /wp-content/uploads/2024/11/Sans-titre-1-2048x760.png 2048w, /wp-content/uploads/2024/11/Sans-titre-1-750x278.png 750w, /wp-content/uploads/2024/11/Sans-titre-1-1140x423.png 1140w" sizes="(max-width: 2513px) 100vw, 2513px" /></a></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://achrafbenalaya-ekgvbjdjgta4b4hz.francecentral-01.azurewebsites.net/2024/11/02/powershell-automation-for-azure-networks-detailed-vnet-and-subnet-analysis/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2011</post-id>	</item>
	</channel>
</rss>
