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
CodePudding user response:
netsh advfirewall firewall show rule name="Open Port 80-90" > NUL 2>&1
IF ERRORLEVEL 1 (
netsh advfirewall firewall add rule name= "Open Port 80-90" dir=in action=allow protocol=TCP localport=80-90
) ELSE (
ECHO Rule already exists
)
is simpler.
The netsh
command sets errorlevel
to 0 if the rule exists, non-zero otherwise.
CodePudding user response:
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.