0

I think there's a problem with this if statement.

Function Get-IsFirewallProfileEnabled([string]$profile)
{
    Return [bool](Get-NetFirewallProfile -name "Domain" | Where Enabled -eq "False")
}


# If the firewall for some of the 3 profiles is not enabled
if ( ((Get-IsFirewallProfileEnabled("Domain")) -or (Get-IsFirewallProfileEnabled("Private")) -or (Get-IsFirewallProfileEnabled("Public"))) -eq "False")
{
    Write-Output "Enabling..."
    # Enable Windows firewall for for all (the 3 profiles)
    Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True
}

Whether I have activated a firewall or not, this script always does nothing. What's happening?


SOLUTION

# Now this function is dynamic
Function Get-IsFirewallProfileEnabled([string]$profile)
{
    Return [bool](Get-NetFirewallProfile -name $profile | Where Enabled -eq "True")
}


# If the firewall for some of the 3 profiles is not enabled
if ( -not(Get-IsFirewallProfileEnabled("Domain")) -or -not(Get-IsFirewallProfileEnabled("Private")) -or -not(Get-IsFirewallProfileEnabled("Public")) )
{
    Write-Output "Enabling..."
    # Enable Windows firewall for for all (the 3 profiles)
    Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled True
}

2 Answers 2

2

As Robert mentioned, you are using the string False, not the Boolean $false in your if statement.

But the logic in your if statement isn't working as expected:

if(((Boolean) -or (Boolean) -or (Boolean)) -eq $false)

will not produce the desired result in Powershell (it will only execute if all of the values are $false). Since if always executes on $true, you can achieve desired results by simply -not-ing the values from Get-IsFirewallProfileEnabled like so:

if((-not(Get-IsFirewallProfileEnabled("Domain")) -or (-not(Get-IsFirewallProfileEnabled("Private")) -or (-not(Get-IsFirewallProfileEnabled("Public")))

This will execute the if block when any of the values are $false.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this better IF statement didn't work before, so I programmed this worse IF, haha, thx.
1

You want to use $false not "False".

"False" is a string literal and will never match if the boolean value returned by the condition ((Get-IsFirewallProfileEnabled("Domain")) -or (Get-IsFirewallProfileEnabled("Private")) -or (Get-IsFirewallProfileEnabled("Public"))) is false.

For example:

if ("False") { write-host "true" }

The line above will always write "true" to the host. This is because a non-empty string literal equates to $true.

The line below will never write "true" to the host.

if ($false) { write-host "yes" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.