AzureToolsBD09.psm1

function Get-AzVmAsgAssociation {
  <#
  .SYNOPSIS
    This command shows the association between the Azure VMs and any ASG they may be associated with
  .DESCRIPTION
    Because it is difficult to see which VMs are associated with ASGs in the Azure Portal, This
    command retrieves the inforation about which VMS are associated with which ASG and displays
    the information regarding ASG name, Network Interface Name, NIC Id and VM Name
  .PARAMETER AsgName
    You can specify which ASGs to match, if you do not select any, all ASGs will be assumed
  .NOTES
    Created By: Brent Denny
    Created On: 26-Jun-2024
  .EXAMPLE
    Get-AzVmAsgAssociation -AsgName ASG1
    This will display all Azure VMs that are associated with ASG1
  .EXAMPLE
    Get-AzVmAsgAssociation
    This will display all Azure VMs that are associated all ASGs
  #>

  [CmdletBinding()]
  Param ([string]$AsgName = '')
  
  try {
    if ($AsgName -eq '') {$AllAzAsgs   = Get-AzApplicationSecurityGroup}
    else {$AllAzAsgs = Get-AzApplicationSecurityGroup -Name $AsgName -ErrorAction Stop}
  }
  catch {
    Write-Warning "No ASG with the name of $AsgName can be found"
    break
  }
  $AllAzNics   = Get-AzNetworkInterface
  $AllAzVms    = Get-AzVm

  $Results = @()
  foreach ($Asg in $AllAzAsgs) {
    foreach ($Interface in $AllAzNics) {
      $InterfaceAssociatedAsgs = $Interface.IpConfigurations.ApplicationSecurityGroupstext | ConvertFrom-Json
      if ($Asg.Id -in $InterfaceAssociatedAsgs.Id) {
        $Results += [PSCustomObject]@{
          AsgName = $Asg.Name
          NicName = $Interface.Name
          NicId   = $Interface.Id
          VMName  = ($AllAzVms | Where-Object {
            $_.NetworkProfile.NetworkInterfaces.id -contains $Interface.Id
          }).Name
        }
      }
    }
  }
  return $Results
}