0

I am not a bro in batch scripts, but i can adapt. I am trying to make a batch file that will check the firewall state, and toggle it(ON/OFF).
Note: [the output of the command contain ON or OFF in it's output alongside with other strings].

set "result=" netsh advfirewall show allprofiles state

IF not x%result:ON=%==x%result% (
    ::Disable Firewall
    NetSh Advfirewall set allprofiles state off
) ELSE (
    ::Enable Firewall
    NetSh Advfirewall set allprofiles state on
)

the problem as you see the result variable only contain the last line of the command output, so how to store the multi-line output of the command in a variable without having to store the command's output in a file as it seems redundant.

Black Block
  • 159
  • 1
  • 7
  • 1
    This is technically not a duplicate, because the OP does not require the use a [tag:for-loop] or need to `set` variables to the result of a command for this. Black Block, you should be able to do it with a single command line: `@NetSh AdvFirewall Show CurrentProfile State|Find "ON">NUL&&(NetSh AdvFirewall Set CurrentProfile State OFF)||NetSh AdvFirewall Set CurrentProfile State ON`. – Compo Oct 14 '19 at 15:03
  • (Note: the output of `netsh` is language dependent) – Stephan Oct 14 '19 at 15:27
  • I'm aware of that myself @Stephan, but it's certainly worthy of mention for future readers. In this case, the OP used `ON` in their code, so I was confident in its use for my commented solution. – Compo Oct 14 '19 at 15:32
  • @Compo: yes, I'm sure, you are. My comment was intended for future searchers `:)` – Stephan Oct 14 '19 at 15:42

1 Answers1

0

You should be able to do it with a single command line without the need for variables or the use of a :

@NetSh AdvFirewall Show CurrentProfile State|Find "ON">NUL&&(NetSh AdvFirewall Set CurrentProfile State OFF)||NetSh AdvFirewall Set CurrentProfile State ON

For an extended version, also ensures that inbound and outbound rules are set. (Please note that these are examples only, not recommendations and have been provided to better show the layout of the original suggestion when split over multiple lines):

@Echo Off
NetSh AdvFirewall Show CurrentProfile State | Find "ON" >NUL && (
    NetSh Advfirewall Set CurrentProfile FirewallPolicy BlockInboundAlways,AllowOutbound
    NetSh AdvFirewall Set CurrentProfile State OFF
) || (
    NetSh AdvFirewall Set CurrentProfile State ON
    NetSh Advfirewall Set CurrentProfile FirewallPolicy AllowInbound,AllowOutbound
)

Please note that these are language dependent, so may need adjustment if your system language is not English.

If you are not a member of the Administrators group, and UAC is enabled on your PC, run the script as administrator.

Compo
  • 36,585
  • 5
  • 27
  • 39