Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

PowerShell Script to Enable or Disable Windows Firewall Profiles

Ensuring the security of networks and systems is a cornerstone of IT. One of the primary defenses in a Windows environment is the Windows Firewall. By controlling the flow of inbound and outbound traffic, it acts as a gatekeeper. This article delves into a PowerShell script that provides a streamlined method to enable or disable Windows Firewall profiles, a crucial task for IT professionals.

Background

The script presented is designed to enable or disable all Windows Firewall profiles, namely Domain, Public, and Private. These profiles determine the settings and rules applied based on the network type a computer is connected to. For Managed Service Providers (MSPs) and IT professionals, a tool that can quickly toggle these profiles is invaluable. Whether for troubleshooting, security hardening, or network configuration, this script offers a swift solution.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Enable or disable all Windows Firewall profiles(Domain, Public, Private).
.DESCRIPTION
    Enable or disable all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Disable
    Disables all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Enable
    Enables all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Enable -BlockAllInbound
    Enables all Windows Firewall profiles(Domain, Public, Private).
    Blocks all inbound traffic on the Domain, Public, Private profiles
.OUTPUTS
    String[]
.OUTPUTS
    PSCustomObject[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ProtocolSecurity
#>

[CmdletBinding(DefaultParameterSetName = "Enable")]
param (
    [Parameter(
        Mandatory = $true,
        ParameterSetName = "Enable"
    )]
    [Switch]
    $Enable,
    [Parameter(
        Mandatory = $true,
        ParameterSetName = "Disable"
    )]
    [Switch]
    $Disable,
    [Parameter(
        ParameterSetName = "Enable"
    )]
    [Switch]
    $BlockAllInbound
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not $(Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if ($(Get-Command "Get-NetFirewallProfile" -ErrorAction SilentlyContinue).Name -like "Get-NetFirewallProfile") {
        # Use Get-NetFirewallProfile if available
        try {
            $NetFirewallSplat = @{
                Profile     = @("Domain", "Public", "Private")
                Enabled     = $(if ($Enable) { "True" }elseif ($Disable) { "False" })
                ErrorAction = "Stop"
            }
            if ($Enable -and $BlockAllInbound) {
                $NetFirewallSplat.Add('DefaultInboundAction', 'Block')
                $NetFirewallSplat.Add('DefaultOutboundAction', 'Allow')
            }
            Set-NetFirewallProfile @NetFirewallSplat
            
        }
        catch {
            Write-Error $_
            Write-Host "Failed to turn $(if ($Enable) { "on" }elseif ($Disable) { "off" }) the firewall."
            exit 1
        }
        # Proof of work
        Get-NetFirewallProfile -ErrorAction Stop | Format-Table Name, Enabled        
    }
    else {
        # Fall back onto netsh
        netsh.exe AdvFirewall set AllProfiles state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set DomainProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set PrivateProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set PublicProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        
        if ($Enable -and $BlockAllInbound) {
            try {
                netsh.exe AdvFirewall set DomainProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
                netsh.exe AdvFirewall set PrivateProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
                netsh.exe AdvFirewall set PublicProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
            }
            catch {
                Write-Error $_
                Write-Host "Could not set Block All Inbound Traffic to 1"
            }
        }
        # Proof of work
        netsh.exe AdvFirewall show AllProfiles state
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
    }
}
end {}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

At its core, the script checks for administrator privileges, essential since altering firewall settings requires elevated rights. It then verifies the presence of the Get-NetFirewallProfile cmdlet, a modern PowerShell command for managing firewall profiles.

If this cmdlet is available, the script employs it to either enable or disable the specified profiles. An option to block all inbound traffic, while allowing outbound traffic, adds an extra layer of security.

In the absence of the Get-NetFirewallProfile cmdlet, the script reverts to the older netsh.exe command-line tool.

Potential Use Cases

Consider an IT professional, Jane, at a large corporation. They’re introducing a new application, but during testing, they find the application can’t communicate with its server. Suspecting a firewall issue, Jane uses this script to temporarily disable the firewall profiles, test the application, and then promptly re-enable them. This quick action aids in diagnosing the problem without manual navigation.

Comparisons

The script provides a programmatic approach to managing firewall profiles. Alternatives include the manual adjustment via the Windows Firewall GUI or using Group Policy Objects (GPOs) for domain-joined machines. However, both lack the immediacy of this script.

FAQs

  • Can I run this script on any Windows machine?
    It’s designed for Windows 10 and Windows Server 2016 and above.
  • Do I need special permissions to execute this script?
    Yes, administrator privileges are necessary.

Security Implications

The power to quickly toggle firewall profiles is a double-edged sword. Disabling them, even momentarily, can expose systems to threats. It’s vital to grasp the security implications and ensure systems remain protected.

Recommendations

  • Test the script in a controlled setting first.
  • If you’re disabling the firewall for diagnostics, re-enable it immediately afterward.
  • Regularly review firewall rules to ensure alignment with security policies.

Final Thoughts

Managing Windows Firewall profiles is essential for network and system security. While tools like NinjaOne offer all-encompassing IT management solutions, scripts like the one discussed are invaluable for specific tasks. As always, understanding its workings and implications ensures its effective and secure use.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).