Skip to content

How to List All Windows Firewall Rules in Batch Script

Learn how to export and audit all Windows Firewall rules using Batch scripts with netsh advfirewall or PowerShell for security audits, filtering active rules, and identifying unauthorized port exceptions.

The Windows Firewall is the primary gatekeeper for your system's network security. It contains hundreds of "Rules" that define which applications can talk to the internet and which incoming connections are allowed. Over time, installing and uninstalling software can leave behind a cluttered mess of forgotten rules, potentially creating security holes. A Batch script can use the netsh advfirewall command or PowerShell to generate a comprehensive list of every active firewall rule, allowing you to audit your security posture and identify unauthorized port exceptions.

This guide will explain how to export and list your firewall rules.

Method 1: Using Netsh (Quick Text Summary)

The netsh advfirewall command provides a structured text list of all rules.

@echo off
setlocal

:: Check for Administrator privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] This script requires Administrator privileges.
    echo         Right-click and select "Run as administrator."
    pause
    endlocal
    exit /b 1
)

set "OutputFile=%USERPROFILE%\firewall_rules_all.txt"

echo [AUDIT] Fetching all Windows Firewall rules...
echo         This may take a moment...
echo.

:: Redirect to file - output is too large for the console window
(
    echo ==========================================
    echo  FIREWALL RULES AUDIT
    echo  %COMPUTERNAME% - %date% %time%
    echo ==========================================
    echo.
    netsh advfirewall firewall show rule name=all
) > "%OutputFile%"

:: Count total rules
set "RuleCount=0"
for /f %%n in ('findstr /c:"Rule Name:" "%OutputFile%" ^| find /c /v ""') do set "RuleCount=%%n"

echo [OK] Exported %RuleCount% firewall rules to:
echo      %OutputFile%
echo.
echo [TIP] Open the file in a text editor to review.
echo       Use CTRL+F to search for specific application names or ports.

pause
endlocal

Method 2: Filtering for Active Rules Only

A full list can be thousands of lines long. This method shows only rules that are currently enabled, separated by direction.

@echo off
setlocal enabledelayedexpansion

:: Check for Administrator privileges
net session >nul 2>&1
if !errorlevel! neq 0 (
    echo.
    echo  ###########################################################
    echo  [ERROR] This script requires Administrator privileges.
    echo  Please right-click and "Run as Administrator".
    echo  ###########################################################
    pause
    endlocal
    exit /b 1
)

set "TempFile=%TEMP%\fw_rules.tmp"

echo.
echo  ===========================================================
echo     WINDOWS FIREWALL: ACTIVE RULES AUDIT
echo  ===========================================================
echo  [SCAN] Analyzing firewall configuration...
echo.

:: Capture full rule output once
netsh advfirewall firewall show rule name=all > "%TempFile%" 2>&1

:: --- SECTION 1: ENABLED INBOUND RULES ---
set "InboundCount=0"
echo  [+] ENABLED INBOUND RULES
echo  -----------------------------------------------------------
echo     Rule Name
echo  -----------------------------------------------------------

set "currentRule="
set "isEnabled=0"
set "isInbound=0"

for /f "tokens=1* delims=:" %%a in ('type "%TempFile%"') do (
    set "label=%%a"
    set "value=%%b"

    echo "!label!" | findstr /i "Rule Name" >nul 2>&1
    if !errorlevel! equ 0 (
        if !isEnabled! equ 1 if !isInbound! equ 1 (
            call :PrintRule "!currentRule!"
            set /a InboundCount+=1
        )
        :: Trim leading spaces
        for /f "tokens=* delims= " %%v in ("!value!") do set "currentRule=%%v"
        set "isEnabled=0"
        set "isInbound=0"
    )

    echo "!label!" | findstr /i "Enabled" >nul 2>&1
    if !errorlevel! equ 0 (
        echo "!value!" | findstr /i "Yes" >nul 2>&1
        if !errorlevel! equ 0 set "isEnabled=1"
    )

    echo "!label!" | findstr /i "Direction" >nul 2>&1
    if !errorlevel! equ 0 (
        echo "!value!" | findstr /i "In" >nul 2>&1
        if !errorlevel! equ 0 set "isInbound=1"
    )
)

:: Final rule check
if !isEnabled! equ 1 if !isInbound! equ 1 (
    call :PrintRule "!currentRule!"
    set /a InboundCount+=1
)

echo  -----------------------------------------------------------
echo     Total Enabled Inbound: !InboundCount!
echo.

:: --- SECTION 2: ENABLED OUTBOUND RULES ---
set "OutboundCount=0"
echo  [+] ENABLED OUTBOUND RULES
echo  -----------------------------------------------------------
echo     Rule Name
echo  -----------------------------------------------------------

set "currentRule="
set "isEnabled=0"
set "isInbound=0"

for /f "tokens=1* delims=:" %%a in ('type "%TempFile%"') do (
    set "label=%%a"
    set "value=%%b"

    echo "!label!" | findstr /i "Rule Name" >nul 2>&1
    if !errorlevel! equ 0 (
        if !isEnabled! equ 1 if !isInbound! equ 0 (
            call :PrintRule "!currentRule!"
            set /a OutboundCount+=1
        )
        :: Trim leading spaces
        for /f "tokens=* delims= " %%v in ("!value!") do set "currentRule=%%v"
        set "isEnabled=0"
        set "isInbound=0"
    )

    echo "!label!" | findstr /i "Enabled" >nul 2>&1
    if !errorlevel! equ 0 (
        echo "!value!" | findstr /i "Yes" >nul 2>&1
        if !errorlevel! equ 0 set "isEnabled=1"
    )

    echo "!label!" | findstr /i "Direction" >nul 2>&1
    if !errorlevel! equ 0 (
        echo "!value!" | findstr /i "Out" >nul 2>&1
        if !errorlevel! equ 0 set "isInbound=0"
    )
)

:: Final rule check
if !isEnabled! equ 1 if !isInbound! equ 0 (
    call :PrintRule "!currentRule!"
    set /a OutboundCount+=1
)

echo  -----------------------------------------------------------
echo     Total Enabled Outbound: !OutboundCount!
echo.

:: --- SUMMARY SECTION ---
echo  ===========================================================
echo     FINAL SUMMARY
echo  ===========================================================
echo     Inbound Active:  !InboundCount!
echo     Outbound Active: !OutboundCount!
echo  ===========================================================
echo.
echo  [TIP] Focus your security audit on INBOUND rules.
echo        These are the "open doors" into your machine.
echo.

:: Clean up
del "%TempFile%" >nul 2>&1
pause
endlocal
exit /b


:PrintRule
    echo     - %~1
    exit /b

Example of Output:


 ===========================================================
    WINDOWS FIREWALL: ACTIVE RULES AUDIT
 ===========================================================
 [SCAN] Analyzing firewall configuration...

 [+] ENABLED INBOUND RULES
 -----------------------------------------------------------
    Rule Name
 -----------------------------------------------------------
    - Microsoft 365 Copilot
    - Microsoft Edge (mDNS-In)
    - Microsoft Copilot (mDNS-In)

 [+] ENABLED OUTBOUND RULES
 -----------------------------------------------------------
    Rule Name
 -----------------------------------------------------------
    - Microsoft 365 Copilot
    - Microsoft Edge (mDNS-Out)
    - Microsoft Copilot (mDNS-Out)

 ===========================================================
    FINAL SUMMARY
 ===========================================================
    Inbound Active:  3
    Outbound Active: 3
 ===========================================================

 [TIP] Focus your security audit on INBOUND rules.
       These are the "open doors" into your machine.

Method 3: Detailed Audit with PowerShell (CSV Export)

PowerShell provides much deeper information, including application paths, port numbers, and protocol details, exported to a CSV you can open in Excel.

@echo off
setlocal

:: Check for Administrator privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] This script requires Administrator privileges.
    pause
    endlocal
    exit /b 1
)

set "OutputFile=%USERPROFILE%\Firewall_Audit.csv"

echo [REPORT] Generating detailed Firewall audit CSV...
echo          This may take a minute on systems with many rules...
echo.

powershell -NoProfile -Command ^
  "try {"^
  "  $rules = Get-NetFirewallRule -ErrorAction Stop;"^
  "  $results = @();"^
  "  $count = 0;"^
  "  foreach ($rule in $rules) {"^
  "    $count++;"^
  "    if ($count %% 50 -eq 0) { Write-Host ('  Processing rule {0} of {1}...' -f $count, $rules.Count) };"^
  "    $portFilter = $rule | Get-NetFirewallPortFilter -ErrorAction SilentlyContinue;"^
  "    $appFilter = $rule | Get-NetFirewallApplicationFilter -ErrorAction SilentlyContinue;"^
  "    $addrFilter = $rule | Get-NetFirewallAddressFilter -ErrorAction SilentlyContinue;"^
  "    $results += [PSCustomObject]@{"^
  "      RuleName     = $rule.DisplayName;"^
  "      Enabled      = $rule.Enabled;"^
  "      Direction    = $rule.Direction;"^
  "      Action       = $rule.Action;"^
  "      Profile      = $rule.Profile;"^
  "      Protocol     = $portFilter.Protocol;"^
  "      LocalPort    = $portFilter.LocalPort;"^
  "      RemotePort   = $portFilter.RemotePort;"^
  "      Application  = $appFilter.Program;"^
  "      RemoteAddress = $addrFilter.RemoteAddress;"^
  "    }"^
  "  };"^
  "  $results | Export-Csv -Path '%OutputFile%' -NoTypeInformation;"^
  "  Write-Host '';"^
  "  Write-Host ('[OK] Exported {0} rules to: %OutputFile%' -f $results.Count);"^
  "  Write-Host '';"^
  "  $enabledInbound = ($results | Where-Object { $_.Enabled -eq 'True' -and $_.Direction -eq 'Inbound' -and $_.Action -eq 'Allow' }).Count;"^
  "  $enabledOutbound = ($results | Where-Object { $_.Enabled -eq 'True' -and $_.Direction -eq 'Outbound' -and $_.Action -eq 'Allow' }).Count;"^
  "  Write-Host '  === SECURITY SUMMARY ===';"^
  "  Write-Host ('  Total rules:              {0}' -f $results.Count);"^
  "  Write-Host ('  Enabled inbound ALLOW:    {0}' -f $enabledInbound);"^
  "  Write-Host ('  Enabled outbound ALLOW:   {0}' -f $enabledOutbound);"^
  "  Write-Host '  =========================';"^
  "} catch {"^
  "  Write-Host ('[ERROR] ' + $_.Exception.Message)"^
  "}"

echo.

if exist "%OutputFile%" (
    echo [SUCCESS] Open %OutputFile% in Excel to review and filter.
) else (
    echo [ERROR] CSV file was not created. Check permissions and PowerShell errors above.
)

pause
endlocal

Method 4: Security-Focused Inbound Audit

Specifically designed for security auditing, this method shows only enabled inbound ALLOW rules with their ports and applications, flagging potential risks.

@echo off
setlocal

:: Check for Administrator privileges
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] This script requires Administrator privileges.
    pause
    endlocal
    exit /b 1
)

echo [SECURITY] Inbound Firewall Rule Audit
echo        Showing enabled rules that ALLOW inbound connections...
echo.

powershell -NoProfile -Command ^
  "$rules = Get-NetFirewallRule -Direction Inbound -Action Allow -Enabled True -ErrorAction SilentlyContinue;"^
  "if (-not $rules) {"^
  "  Write-Host '[INFO] No enabled inbound ALLOW rules found.';"^
  "  exit 0"^
  "};"^
  ""^
  "Write-Host ('  {0,-40} {1,-10} {2,-15} {3}' -f 'RULE NAME','PROTOCOL','LOCAL PORT','APPLICATION');"^
  "Write-Host ('  ' + '-' * 90);"^
  ""^
  "$warnings = 0;"^
  "foreach ($rule in $rules) {"^
  "  $port = ($rule | Get-NetFirewallPortFilter -EA SilentlyContinue);"^
  "  $app = ($rule | Get-NetFirewallApplicationFilter -EA SilentlyContinue);"^
  "  $proto = if ($port.Protocol) { $port.Protocol } else { 'Any' };"^
  "  $localPort = if ($port.LocalPort -eq 'Any') { 'Any' } else { $port.LocalPort -join ',' };"^
  "  $appPath = if ($app.Program -and $app.Program -ne 'Any') { Split-Path $app.Program -Leaf } else { 'Any' };"^
  ""^
  ""^
  "  $flag = '';"^
  "  if ($localPort -eq 'Any' -and $appPath -eq 'Any') { $flag = ' [!! WIDE OPEN]'; $warnings++ };"^
  "  if ($proto -eq 'Any') { $flag += ' [! ANY PROTO]'; $warnings++ };"^
  ""^
  "  Write-Host ('  {0,-40} {1,-10} {2,-15} {3}{4}' -f $rule.DisplayName.Substring(0,[Math]::Min(40,$rule.DisplayName.Length)), $proto, $localPort, $appPath, $flag)"^
  "};"^
  ""^
  "Write-Host ('  ' + '-' * 90);"^
  "Write-Host '';"^
  "Write-Host ('  Total enabled inbound ALLOW rules: ' + $rules.Count);"^
  "if ($warnings -gt 0) {"^
  "  Write-Host '';"^
  "  Write-Host ('  [ALERT] {0} potentially risky rule(s) found!' -f $warnings) -ForegroundColor Yellow;"^
  "  Write-Host '  Rules marked [!! WIDE OPEN] allow ANY port from ANY application.' -ForegroundColor Yellow;"^
  "  Write-Host '  Review these rules carefully.' -ForegroundColor Yellow"^
  "}"

echo.
pause
endlocal

Example of Output:

[SECURITY] Inbound Firewall Rule Audit
       Showing enabled rules that ALLOW inbound connections...

  RULE NAME                                PROTOCOL   LOCAL PORT      APPLICATION
  ------------------------------------------------------------------------------------------
  World Wide Web Services (HTTPS Traffic-I TCP        443             System
  World Wide Web Services (HTTP Traffic-In TCP        80              System
  Remote Desktop - Shadow (TCP-In)         TCP        Any             RdpSa.exe
  Remote Desktop - User Mode (UDP-In)      UDP        3389            svchost.exe
  Remote Desktop - User Mode (TCP-In)      TCP        3389            svchost.exe

How to Avoid Common Errors

Wrong Way: Using netsh firewall (Deprecated)

The netsh firewall command is deprecated and was replaced by netsh advfirewall in Windows Vista. Using the old command returns partial or incorrect results on modern Windows versions.

Correct Way: Always use netsh advfirewall. It is the modern standard and provides access to all advanced firewall properties:

:: Correct
netsh advfirewall firewall show rule name=all

:: Wrong (deprecated)
netsh firewall show config

Wrong Way: Displaying All Rules in the Console

A typical system has 300–500+ rules. Dumping them all to the console window means they scroll past instantly, and cmd.exe's limited scroll buffer truncates the beginning.

Correct Way: Always redirect to a file or export to CSV:

:: Text file
netsh advfirewall firewall show rule name=all > firewall_rules.txt

:: CSV via PowerShell (Method 3)

Wrong Way: Running Without Administrator Privileges

Querying the firewall configuration requires elevation. Without it, commands return "Access Denied" or incomplete results.

Correct Way: Always check for elevation at the start:

net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [ERROR] Run as Administrator.
    exit /b 1
)

Wrong Way: Only Checking Rule Names Without Port/Application Details

A rule named "Allow Web Traffic" tells you nothing about what port it actually opens or which executable it applies to. Without these details, you can't determine if a rule is legitimate.

Correct Way: Use Method 3 or 4, which query Get-NetFirewallPortFilter and Get-NetFirewallApplicationFilter to get the actual port numbers and application paths.

Problem: Rules with findstr Pattern Matching

You can use findstr /C:"Enabled: *Yes" to find enabled rules. However, findstr with /C: treats the pattern as a literal string: the * is not a wildcard. This means the filter may miss rules where spacing varies.

Solution: Use findstr /i "Yes" separately after filtering for the "Enabled" line, or use the multi-line block parsing approach shown in the updated Method 2.

Best Practices and Rules

1. Distinguish Profiles

Windows Firewall has three profiles: Domain, Private, and Public. A rule might be allowed on your "Private" home network but blocked on "Public" Wi-Fi. Check the profile column in your audit:

:: Show which profile is currently active
netsh advfirewall show currentprofile

2. Focus on Inbound Rules

Focus your security audit on Inbound ALLOW rules. These are the rules that allow the outside world to initiate a connection to your computer. Method 4 is specifically designed for this purpose.

3. Flag "Wide Open" Rules

Rules that allow Any port with Any application are the most dangerous. They effectively create an unrestricted hole in your firewall. Method 4 automatically flags these rules.

4. Save a Baseline

When you first set up a machine, export the firewall rules as a baseline. Periodically re-export and compare to detect unauthorized rule additions:

:: Create baseline
powershell -NoProfile -Command "Get-NetFirewallRule | Select DisplayName, Enabled, Direction, Action | Export-Csv baseline.csv -NoTypeInformation"

:: Later: compare
fc baseline.csv current.csv

5. Check for Unknown Applications

In the CSV export (Method 3), sort by the "Application" column. Any .exe path you don't recognize deserves investigation, it could be leftover from uninstalled software or, worse, malware that created its own firewall exception.

6. Always Use setlocal / endlocal

Without setlocal, every variable your script creates persists in the parent shell session, causing potential conflicts when running multiple scripts in sequence.

Conclusions

Listing your Windows Firewall rules is a foundational step in professional system security. By moving from GUI-based management to automated command-line auditing, you gain the ability to quickly spot suspicious changes and maintain a clean, hardened network perimeter. This proactive visibility ensures that your Windows environment remains protected and that only legitimate, trusted applications have access to your network.

Navigation