List-AllNSGRules.psm1

<#
 .Synopsis
  List All NSGs along with the Security Rules for a Subscription.
 
 .Description
  List All NSGs along with the Security Rules for a Subscription.
 
 .Parameter Port
  None.
 
 .Example
   #List All NSGs along with the Security Rules for a Subscription.
   List-AllNSGRules
 
#>


#------------------------------------------------------------------------------
#
#
# THIS CODE AND ANY ASSOCIATED INFORMATION ARE PROVIDED “AS IS” WITHOUT
# WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS
# FOR A PARTICULAR PURPOSE. THE ENTIRE RISK OF USE, INABILITY TO USE, OR
# RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
#
#------------------------------------------------------------------------------




Function List-AllNSGRules(){

Param ()


#To change the Format Limit
$x = $FormatEnumerationLimit 
$FormatEnumerationLimit  = -1

$nsgall = Get-AzNetworkSecurityGroup
$SubID = $nsgall.id | ForEach-Object {$_ -replace "resourceGroups/.*" -replace ".*/Subscriptions" -replace "/"}
$SubID = $Subid[0]
$outfile = $HOME+'\'+$SubID+'-NSG.txt'

$Time = Get-Date
$Time = $Time.ToUniversalTime()

"Subscription ID: $SubID" | Out-File $outfile -Append
"Date : $time UTC `n" | Out-File $outfile -Append

Write-Host "All NSGs and Rules for the Subscription: $Subid `nWill be written into the file: $outfile" -ForegroundColor Green
for ($i=0; $i -lt $nsgall.Count;$i++){
"NSG Name: $($nsgall.name[$i])" | Out-File $outfile -Append
"Resource Group: $($nsgall.Resourcegroupname[$i])" | Out-File $outfile -Append
$nsgone = Get-AzNetworkSecurityGroup -Name $nsgall.name[$i] -ResourceGroupName $nsgall.Resourcegroupname[$i]
"----------------------------- `t" | Out-File $outfile  -Append
$nsgone.SecurityRules | FL -Property Name, Description, Protocol, SourcePortRange, DestinationPortRange, SourceAddressPrefix, DestinationAddressPrefix, Access, Priority, Direction, ProvisioningState | Out-File $outfile  -Append
"----------------------------- `n" | Out-File $outfile  -Append 

} 
start-process $home

# To set the format limit back to normal
$FormatEnumerationLimit = $x
#$FormatEnumerationLimit
Get-Content $outfile

}

Export-ModuleMember -Function List-AllNSGRules