Search code examples
batch-filenetsh

How to check firewall rule before creating it using batch script and netsh


I am attempting to create a batch file that user will just run and it will add a firewall rule, the script works but i want to prevent the user to creating multiple rules with the same name.

I know how to check it using netsh -contains but not sure how to convert it to a batch script.

my existing script

@Echo On
netsh advfirewall firewall add rule name= "Open Port 80-90" dir=in action=allow protocol=TCP localport=80-90

Exit

what i am trying to do

@Echo On
if netsh advfirewall firewall show rule name="Open Port 80-90" -contains "No rules match the specified criteria."
 
    @Echo On
    netsh advfirewall firewall add rule name= "Open Port 80-90" dir=in action=allow protocol=TCP localport=80-90

Exit

Solution

  • This should do it:

    netsh advfirewall firewall show rule name="Open Port 80-90" | findstr /c:"No rules match the specified criteria." > NUL 2>&1
        IF %ERRORLEVEL% EQU 0 (
            netsh advfirewall firewall add rule name= "Open Port 80-90" dir=in action=allow protocol=TCP localport=80-90
        ) ELSE (
            ECHO Rule already exists
        )
    

    Should be pretty self-explanatory. %ERRORLEVEL% in this case is capturing the errorlevel of findstr, which will be 0 if the specified string is found.