Enable windows firewall powershell

Эта статья посвящена основам управления настройками и правилами встроенного Windows Defender Firewall из командной строки PowerShell. Мы рассмотрим, как включать/отключать брандмауэр для различных профилей, создавать, редактировать и удалять правила, экспортировать/импортировать правила Windows Firewall с помощью PowerShell.

Содержание:

  • Как включить и отключить Windows Defender Firewall через PowerShell?
  • Создать новое правило Windows Firewall
  • Изменить правило Windows Firewall с помощью PowerShell
  • Включить/отключить правило Windows Defender Firewall
  • PowerShell: вывести список активных правил Windows Firewall

Для управления настройками Windows Firewall обычно используется отдельная графическая MMC оснастка
wf.msc
(Control Panel -> System and Security -> Windows Defender Firewall -> Advanced settings). Большинство операций по настройке и управлению параметрами Windows Firewall можно выполнять из командной строки PowerShell. Для этого, начиная с версии Windows PowerShell 5.1, можно использовать встроенный модуль NetSecurity

Полный список командетов в модуле NetSecurity можно вывести с помощью команды:

Get-Command -Module NetSecurity

модуль NetSecurity для управления Windows Defender Firewall из PowerShell

Раньше для управления правилами и настройками Брандмауэра Windows использовалась команда
netsh advfirewall firewall
.

Как включить и отключить Windows Defender Firewall через PowerShell?

По умолчанию Defender Firewall в Windows включен.

Get-NetFirewallProfile | Format-Table Name, Enabled

отключить windows firewall с помощью powershell

Как вы видите, в Windows Firewall есть три типа сетевых профилей:

  • Domain (Доменный) – применяется к компьютерам, включенным в домен Active Directory;
  • Private (Частный) – домашние или рабочие сети;
  • Public (Общий) – общедоступные сети.

В настройках профилей по-умолчанию разрешены все исходящие подключения и блокируется входящие (кроме разрешенных).

windows defender firewall включен в windows

Информация о типах сетей хранится службой Network Location Awareness (NLA) в базе данных. Вы можете изменить профиль сети в Windows, если он определился некорректно.

Каждый профиль может отличаться используемым набором правил файервола. По умолчанию все сетевые интерфейсы компьютера защищены фаейрволом и к ним применяются все три типа профилей.

Чтобы полностью отключить Firewall в Windows, выполните команду:

Set-NetFirewallProfile -All -Enabled False

Либо укажите конкретный профиль вместо All:

Set-NetFirewallProfile -Profile Public -Enabled False

Чтобы включить файервол для всех трех сетевых профилей, используется команда:

Set-NetFirewallProfile -All -Enabled True

Вывести тип профиля, который применяется к сетевому подключению:

Get-NetConnectionProfile

В этом примере к сетевому подключению Ethernet0 применяется доменный профиль (DomainAuthenticated).

Вы можете управлять правилами Windows Firewall на удаленных компьютерах, если на них настроен PowerShell Remoting (WinRM). В этом примере с помощью командлета Invoke-Command мы отключим файервол на удаленных компьютерах из списка:

$computers = @('PC01', 'PC02', 'PC03')
Invoke-Command -ComputerName $computers {Set-NetFirewallProfile -All -Enabled False}

Можно изменить действие по-умолчнию для профиля Public и заблокировать все входящие подключения.

Set-NetFirewallProfile –Name Public –DefaultInboundAction Block

Текущие настройки профиля можно вывести так:

Get-NetFirewallProfile -Name Public

настройки по умолчанию для public профиля Windows Firewall

Если вы управляете настройками Windows Firewall через GPO, вы можете вывести текущие результирующие настройки профилей так:

Get-NetFirewallProfile -policystore activestore

Проверим, что все параметры брандмауэра применяются ко всем сетевым интерфейса компьютера.

Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases

Если все интерфейсы защищены, команда должна вернуть:

DisabledInterfaceAliases : {NotConfigured}

Get-NetFirewallProfile

Можно отключить определенный профиль для интерфейса (вывести список имен интерфейсов можно с помощью командлета Get-NetIPInterface).

Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases "Ethernet0"

Как вы видите, теперь профиль Public не применяется к интерфейсу Ethernet0:

DisabledInterfaceAliases : {Ethernet0}

Set-NetFirewallProfile - изсенить настройки профиля Firewall

С помощью командлета
Set-NetFirewallProfile
вы можете изменить параметры профиля (действие по-умолчанию, журналирование, путь и размер лог файла, настройки оповещений и т.д.).

Вы можете настроить параметры логирования сетевых подключений на уровне каждого профиля. По умолчанию журналы Windows Firewall хранятся в каталоге
%systemroot%\system32\LogFiles\Firewall
, размер файла – 4 Мб. Вы можете изменить включить журналирование подключений и увеличить максимальный размер файла:

Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

Создать новое правило Windows Firewall

Для управления правилами брандмауэра используются 9 командлетов:

  • New-NetFirewallRule
  • Copy-NetFirewallRule
  • Disable-NetFirewallRule
  • Enable-NetFirewallRule
  • Get-NetFirewallRule
  • Remove-NetFirewallRule
  • Rename-NetFirewallRule
  • Set-NetFirewallRule
  • Show-NetFirewallRule

Рассмотрим несколько простых примеров открытия портов в Windows Firewall.

Например, вы хотите разрешить входящие TCP подключения на порты 80 и 443 для профилей Domain и Private. Воспользуйтесь такой командой:

New-NetFirewallRule -DisplayName 'WEB-Inbound' -Profile @('Domain', 'Private') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80', '443')

New-NetFirewallRule - создать новое правило Windows Firewall с помощью PowerShell

Вы можете разрешить или заблокировать трафик для конкретной программы. Например, вы хотите заблокировать исходящие соединения для FireFox:

New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox” -Description “Block Firefox” -Direction Outbound

Разрешим входящее RDP подключение по стандартному порту TCP\3389 только с одного IP адреса:

New-NetFirewallRule -DisplayName "AllowRDP" –RemoteAddress 192.168.1.55 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow

Чтобы разрешить ICMP ping для адресов из указанных диапазонов IP адресов и подсети, используйте команды:

$ips = @("192.168.1.50-192.168.1.60", "192.165.2.22-192.168.2.200", ”10.10.0.0/16”)

New-NetFirewallRule -DisplayName "Allow inbound ICMPv4" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow

New-NetFirewallRule -DisplayName "Allow inbound ICMPv6" -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow

Добавить в правило файервола список IP адресов из текстового файла (по одному IP в строке):

$ips=Get-Content C:\temp\ip.txt
Get-NetFirewallrule -DisplayName 'AllowRDP'|Set-NetFirewallRule -RemoteAddress $ips

В предыдущей статье мы показывали как с помощью PowerShell можно заблокировать доступ к сайтам не только по IP адресу, но и по DNS имени домена/сайта.

Разрешить все входящие подключения с указанного IP адреса (добавить адрес в белый список):

$IP = '192.168.1.20'
New-NetFirewallRule -DisplayName "Allow $IP" -Direction Inbound -Action Allow -RemoteAddress $IP

Изменить правило Windows Firewall с помощью PowerShell

Чтобы отредактировать правило брандмауэра, используется командлет Set-NetFirewallRule. Например, вы хотите разрешить входящие подключения с указанного IP адреса для ранее созданного правила:

Get-NetFirewallrule -DisplayName 'WEB-Inbound' | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.20

Если нужно добавить в правило файервола несколько IP адресов, используйте такой скрипт:

$ips = @("192.168.1.50", "192.165.2.22",”192.168.1.21”)
$current_ips = (Get-NetFirewallRule -DisplayName 'WEB-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$current_ips += $ips
Get-NetFirewallrule -DisplayName 'WEB-Inbound'|Set-NetFirewallRule -RemoteAddress $current_ips

Вывести все IP адреса, которые содержатся в правиле брандмауэра:

(Get-NetFirewallrule -DisplayName 'Web-Inbound'|Get-NetFirewallAddressFilter).remoteaddress

Удалить один IP адрес из правила:

$removeip = "192.168.1.21"
$current_ips = (Get-NetFirewallRule -DisplayName 'WEB-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$filterIP = $current_ips | Where-Object{ $_ -notin $removeip }
Get-NetFirewallrule -DisplayName 'WEB-Inbound'|Set-NetFirewallRule -RemoteAddress $filterIP

powershell: добавить ip адрес в правило firewall

Включить/отключить правило Windows Defender Firewall

Вы можете включать/отключать правила файервола с помощью командлетов Disable-NetFirewallRule и Enable-NetFirewallRule.

Disable-NetFirewallRule –DisplayName 'WEB-Inbound'

Чтобы разрешить ICMP (ping), выполните команду:

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

Чтобы удалить правило брандмауэре используется командлет Remove-NetFirewallRule.

Remove-NetFirewallRule -DisplayName 'WEB-Inbound'

Чтобы сбросить все правила Microsoft Defender Firewall и восстановить настройки по умолчанию, выполните команду:

netsh advfirewall reset

или

(New-Object -ComObject HNetCfg.FwPolicy2).RestoreLocalFirewallDefaults()

Это очистит все пользовательские настройки и правила Microsoft Defender Firewall. В списке правил останутся только стандартные правила сетевого доступа Windows.

Перед сбросом можно экспортировать текущие настройки в файл.

netsh advfirewall export "C:\Backup\firewall-config.wfw"

В дальнейшем вы можете вернуть старые настройки файервола, импортировав файл с правилами:

netsh advfirewall import "C:\Backup\firewall-config.wfw"

PowerShell: вывести список активных правил Windows Firewall

Список активных правил для входящего трафика можно вывести так:

Get-NetFirewallRule | where {($_.enabled -eq $True) -and ($_.Direction -eq "Inbound")} |ft

Если, например, нам нужно вывести список блокирующих исходящих правил:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound

Если нужно отобразить имя программы в правиле:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %{$_.Name; $_ | Get-NetFirewallApplicationFilter}

Get-NetFirewallRule вывод правил Windows Firewall

Как вы видите командлет Get-NetFirewallRule не выводит порты сетевые порты и IP адреса для правил брандмауэра. Чтобы вывести всю информацию о разрешенных входящих (исходящих) подключениях в более удобном виде с отображением номеров портов, используйте такой скрипт:

Get-NetFirewallRule -Action Allow -Enabled True -Direction Inbound |
Format-Table -Property Name,
@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,Profile,Direction,Action

Get-NetFirewallRule вывести IP адрес и имя порта

PowerShell предоставляет широкие возможности по управлению правилами Windows Firewall из командной строки. Вы можете автоматически запускать скрипты PowerShell для открытия/закрытия портов при возникновении определенных событий. В следующей статье мы рассмотрим простую систему на базе PowerShell и Windows Firewall для автоматической блокировки IP адресов, с которых выполняется удаленный перебор паролей по RDP на Windows VDS сервере.

In Powershell, you can easily enable or disable Windows Firewall using the Set-NetFirewallProfile command. This cmdlet is used to configure the Firewall’s advanced security settings for a particular, or all, network profile.

While you can also disable Firewall using GUI options like Control Panel/Windows Settings, doing it via CLI options like PowerShell/CMD is more efficient.

Note: Firewall is a key line of defense for your network against unauthorized access and malicious programs. While you can temporarily disable it for testing or other purposes, we advise enabling it afterward.

How to Enable Firewall via Powershell

  1. Press Windows + X to open the quick link menu.
  2. Press and accept the prompt to launch Windows PowerShell (Admin).
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    Set-NetFirewallProfile -Enabled True
  5. Enable Firewall for a specific profile(s):
    Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
    Check the Network Profiles section for more on this.
  6. Check if Firewall is enabled:
    netsh advfirewall show all
    netsh-advfirewall-show-all

How to Disable Firewall via Powershell

  1. Press Windows + X to open the quick link menu.
  2. Press and accept the prompt to launch Windows PowerShell (Admin).
  3. Use the following commands as required. Type them and press Enter after each.
  4. Disable Firewall entirely:
    Set-NetFirewallProfile -Enabled False
  5. Disable Firewall for a specific profile(s):
    Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
    Check the Network Profiles section for more on this.
    Powershell-disable-firewall-domain-public-private

  6. Check if Firewall is disabled:
    netsh advfirewall show all

Remotely Enable/Disable Firewall with Powershell

Note: WinRM needs to be set up beforehand on the target computer for remote disabling to work. Check out How to enable Windows Remote Shell for more on that.

Disable Firewall on One Remote Computer

Replace acer22 with the remote computer’s name and use the following commands:

Enter-PsSession -ComputerName acer22
Set-NetFirewallProfile -All -Enabled False

Powershell-remote-disable-firewall

Disable Firewall On Multiple Remote Computers

Replace acer22 nitro15 dell and so on with the remote computers’ names and add or subtract more names as appropriate. Then use the following commands:

$computers = @(‘acer22', ‘nitro15’, ‘dell’)
$computers | ForEach-Object {
Invoke-Command-ComputerName $_ {
Set-NetFirewallProfile-All -Enabled False
}
}

Remote-disable-firewall-multple-computers

How to Enable/Disable Firewall Using Command Prompt?

In CMD, we’ll use the netsh advfirewall command to enable/disable the firewall. This command also allows for precise control of firewall rules for each of the profiles (Domain, Public, Private).

Enable Firewall via CMD

  1. Press Windows + R to launch Run.
  2. Type cmd and press CTRL + Shift + Enter to launch elevated Command Prompt.
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    netsh advfirewall set allprofiles state on
    cmd-netsh-advfirewall-set-allprofiles-state-on

  5. Enable Firewall for the current profile:
    netsh advfirewall set currentprofile state on
  6. Enable Firewall for a specific profile(s):
    netsh advfirewall set publicprofile state on
    Replace public with domain or private as appropriate. Check the Network Profiles section for more on this.
  7. Check if Firewall is enabled:
    netsh advfirewall show all

Disable Firewall via CMD

  1. Press Windows + R to launch Run.
  2. Type cmd and press CTRL + Shift + Enter to launch elevated Command Prompt.
  3. Use the following commands as required. Type them and press Enter after each.
  4. Enable Firewall entirely:
    netsh advfirewall set allprofiles state off
  5. Enable Firewall for the current profile:
    netsh advfirewall set currentprofile state off
  6. Enable Firewall for a specific profile(s).
    netsh advfirewall set publicprofile state off
    Replace public with domain or private as appropriate. Check the Network Profiles section for more on this.
  7. Check if Firewall is disabled:
    netsh advfirewall show all
    cmd-netsh-advfirewall-show-all

Network Profiles

You can enable/disable the firewall for Domain, Public, Private profiles, or any combination of the three. Simply use the appropriate profiles in the commands above.

  • Domain Profile: This applies to networks where the host system can authenticate to a domain controller. It’s applicable for business environments because of the high level of security and authentication.
  • Private Profile: It is a user-assigned profile designed for trusted networks such as home or work networks. It’s generally safe to turn on Network Discovery and File sharing.
  • Public Profile: It is the default profile, designed for public networks such as public Wi-Fi hotspots. We recommend turning off network discovery and file sharing for security reasons.

Related Questions

How to Enable/Disable Firewall Through GUI?

Enabling/Disabling the firewall via GUI is very simple. To do so:

  1. Press Windows + R to launch Run.
  2. Type windowsdefender://network/ and press Enter to open the Firewall and Network protection window.
  3. Click on your active profile and press the switch to turn the firewall on/off.
    disable-firewall-gui-windows-security

How to Allow an App through Windows Firewall?

A firewall monitors your network traffic and blocks harmful/inappropriate content. Occasionally, it can block or interfere with a trusted app that you need. In such cases, you can allow an app through the firewall with the following steps:

  1. Press Windows + R to launch Run.
  2. Type windowsdefender://network/ and press Enter.
  3. Click on Allow an App through Firewall.
  4. Press Change Settings.
  5. Check the tick box to allow the app through the app. Use Allow Another App if you don’t see your app on the list.
    Windows-Defender-Firewall-Allowed-Apps

  6. Press OK to save the changes.

GUI vs. CLI. Which Is Better For Disabling Firewall?

You can use both GUI (Control Panel, Windows Settings) and CLI (Powershell, Command Prompt) to disable Firewall. It’s just a matter of preference.

Most users prefer GUI (Graphical User Interface) as it’s easier to understand and navigate. But CLI (Command Line Interface) is more efficient as you only need to enter a line of code to accomplish the same thing.

Is It Safe To Disable Windows Firewall?

A firewall is an important layer of security for your network. Ideally, you should use an antivirus along with Windows Firewall for proper protection.

It’s fine to disable the firewall temporarily. But we do not recommend keeping your firewall disabled in the long term. This would leave your network vulnerable to unauthorized access, malicious programs, and other cyber threats.

How to Change Sharing Settings for Network Profiles?

  1. Press Windows + I to launch Settings.
  2. Go to Network and Internet > Ethernet.
  3. Press Change Advanced Sharing Settings on the right.
  4. Adjust sharing settings as appropriate and click Save Changes.
    Network-Advanced-Sharing-Settings

  • Updated on February 13, 2021
  • Powershell, Windows Server

How to enable the Windows Firewall with PowerShell in Windows Server 2012/2016/2019/2022/2025? I recommend turning on the Windows Firewall with PowerShell. But if you have a test lab and you want to keep it disabled for testing, go ahead. Don’t forget to enable the Firewall when you finished testing. In this article, you will learn how to enable the Firewall with PowerShell.

Table of contents

  • Windows Firewall profiles information
  • Get status of the Windows Firewall with PowerShell
  • Enable Windows Firewall in Windows Server 2012/2016/2019/2022/2025
  • Check Windows Firewall status
  • Conclusion

Windows Firewall profiles information

Windows Firewall offers three firewall profiles:

  • Domain profile: applies to networks where the host system can authenticate to a domain controller.
  • Private profile: a user-assigned profile and is used to designate private or home networks.
  • Public profile: this is the default profile. It is used to designate public networks such as Wi-Fi hotspots at coffee shops, airports, and other locations.

Get status of the Windows Firewall with PowerShell

First, let’s get the current status of the Windows Firewall. We will be using the Get-NetFirewallProfile cmdlet.

Get-NetFirewallProfile | Format-Table Name, Enabled

The output appears.

Name    Enabled
----    -------
Domain    False
Private   False
Public    False

We have three profiles: Domain, Name, and Public. Windows Firewall is enabled on all three profiles.

Enable Windows Firewall with PowerShell Windows Firewall is off

In the next step, we are going to enable the Windows Firewall.

Enable Windows Firewall in Windows Server 2012/2016/2019/2022/2025

Enable Windows Firewall on all three profiles.

Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled True

Check Windows Firewall status

Check the status after you enable the Firewall on all three profiles. Run the Get-NetFirewallProfile cmdlet.

Get-NetFirewallProfile | Format-Table Name, Enabled

The output appears.

Name    Enabled
----    -------
Domain     True
Private    True
Public     True
Enable Windows Firewall with PowerShell Windows Firewall is on

Windows Firewall is enabled on all three profiles in Windows Server. It’s important to keep the Windows Firewall turned on.

Conclusion

In this article, you learned how to enable the Firewall in Windows Server 2012/2016/2019/2022/2025. First, get the current status of the Windows Firewall. After that, enable the Windows Firewall with PowerShell.

Did you enjoy this article? If so, you may like Count mailboxes per database in Exchange with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft MVP. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

Post Date:

Last Modified:

Windows Firewall is an essential security feature that protects your system from unauthorized access and threats. If it has been disabled for testing or mistakenly turned off, you can quickly re-enable it using PowerShell.

This guide provides a straightforward process to restore your firewall settings and ensure a secure environment. To enable Windows Firewall with PowerShell, follow these steps:
> Step 1: Understanding Windows Firewall Profiles
> Step 2: Check Current Firewall Status
> Step 3: Enable Windows Firewall


Step 1: Understanding Windows Firewall Profiles

Before running scripts or commands on a computer, it’s important for us to understand what each step is doing. We are enabling the Windows Firewall for all Profiles:
> Domain: For when you are connected to a Domain Controller (computer connected to AD).
> Private: For your home or private networks.
> Public : For public WIFI locations such as coffee shops etc.

Make sure you understand which profile applies to your scenario before proceeding. You can also manage these settings via the GUI for additional clarity:

Windows Firewall status

Step 2: Check Current Firewall Status

Before enabling the firewall, check its current status using the following PowerShell command:

# get local firewall status
Get-NetFirewallProfile | Format-Table Name, Enabled
Get-NetFirewallProfile example

This command retrieves the status of all firewall profiles and displays whether they are enabled (True) or disabled (False).

Step 3: Enable Windows Firewall

To enable the Windows Firewall for all profiles, use the Set-NetFirewallProfile cmdlet. Run the following command in PowerShell or Windows Terminal with admin privileges:

# disable local firewall
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

# get local firewall status
Get-NetFirewallProfile | Format-Table Name, Enabled
enable windows firewall with powershell example

By enabling the firewall, you significantly improve your system’s defense against unauthorized access and potential cyber threats. However, enabling the firewall may block some desired connectivity, requiring you to create new firewall rules to allow specific traffic while maintaining overall security. For detailed guidance on advanced configurations and creating firewall rules, refer to the official Microsoft documentation on the Windows Firewall.


This article covers the basics of managing the settings and rules of the built-in Windows Defender Firewall with Advanced Security from the PowerShell command line. We’ll look at how to enable/disable the firewall for different network profiles, create or remove firewall rules, and import/export Windows Firewall rules with PowerShell.

Contents:

  • How to Turn Windows Defender Firewall On or Off with PowerShell
  • Create Windows Firewall Rules Using PowerShell
  • Modifying an Existing Windows Firewall Rule Using PowerShell
  • How to Enable/Disable/Remove Windows Firewall Rule with PowerShell
  • PowerShell: List Active Rules in Windows Firewall

Windows Firewall settings are typically managed using a separate graphical MMC snap wf.msc (Control Panel -> System and Security -> Windows Defender Firewall -> Advanced settings). You can perform most Windows Firewall configuration and settings management operations from the PowerShell command line. You can use the built-in NetSecurity module to do this (which is available in the version of Windows PowerShell 5.1 or newer).

You can list the available cmdlets in the NetSecurity module by using the command:

Get-Command -Module NetSecurity

powershell NetSecurity on windows 10 to manage windows defender advanced firewall

Previously, the netsh advfirewall firewall command was used to manage Windows Firewall rules and settings.

How to Turn Windows Defender Firewall On or Off with PowerShell

The Windows Defender firewall is enabled by default.

Get-NetFirewallProfile | Format-Table Name, Enabled

There are three types of network profiles in Windows Firewall:

  • Domain – is applied to the computers that are joined to an Active Directory domain;
  • Private – home, SOHO, or workgroup networks;
  • Public – public networks.

By default, the Windows Firewall allows all outbound connections and blocks all inbound connections (except those that are allowed) for each network profile.

The Network Location Awareness (NLA) service stores information about network types in a database. You can manually change the network profile (location) in Windows if it is not detected correctly.

Each network profile (location) may have different firewall rules in use. By default, all of the computer’s network interfaces are protected by a firewall and all three types of profiles are applied to them.

To completely disable the Windows firewall, run the following command

Set-NetFirewallProfile -All -Enabled False

Or specify a specific profile name instead of All:

Set-NetFirewallProfile -Profile Public -Enabled False

In order to enable the Windows Firewall for all three network profiles, use the following command

Set-NetFirewallProfile -All -Enabled True

Displays the type of profile that applies to the network connection:

Get-NetConnectionProfile

The DomainAuthenticated profile is applied to the Ethernet0 network connection in this example.

If PowerShell Remoting (WinRM) is configured on remote computers, you can manage Windows Firewall rules on those computers. In this example, we will use the Invoke-Command cmdlet to connect to remote computers in the list and disable the firewall on them.

$computers = @('WKS01', 'WKS02', 'WKS03')
Invoke-Command -ComputerName $computers {Set-NetFirewallProfile -All -Enabled False}

You can change the default action for the Public profile to block all inbound connections.

Set-NetFirewallProfile –Name Public –DefaultInboundAction Block

The current profile settings can be displayed as follows:

Get-NetFirewallProfile -Name Public

Set-NetFirewallProfile

If you manage Windows Firewall settings using a GPO, you can view the current resulting profile settings as follows:

Get-NetFirewallProfile -policystore activestore

Make sure that all firewall settings are applied to all network interfaces on the computer:

Get-NetFirewallProfile -Name Public | fl DisabledInterfaceAliases

If all interfaces are protected, the command should return:

DisabledInterfaceAliases : {NotConfigured}

Get-NetFirewallProfile

You can disable a particular profile for a network interface ( you can list network adapters in Windows using the Get-NetIPInterface cmdlet):

Set-NetFirewallProfile -Name Public -DisabledInterfaceAliases "Ethernet0"

As you can see, the Public profile is no longer applied to the Ethernet0 interface::

DisabledInterfaceAliases : {Ethernet0}

disable public location for ehernet0 interface

You can use the Set-NetFirewallProfile cmdlet to change the profile settings (default action, logging settings, log file path and size, notification settings, etc.). You can configure network connection logging settings for each network location profile. By default, Windows Firewall logs are stored in %systemroot%\system32\LogFiles\Firewall, and the file size is 4MB. You can enable connection logging and increase the maximum file size:

Set-NetFireWallProfile -Profile Domain -LogBlocked True -LogMaxSize 20000 -LogFileName ‘%systemroot%\system32\LogFiles\Firewall\pfirewall.log’

Create Windows Firewall Rules Using PowerShell

There are 9 PowerShell cmdlets to manage firewall rules on Windows:

  • New-NetFirewallRule
  • Copy-NetFirewallRule
  • Disable-NetFirewallRule
  • Enable-NetFirewallRule
  • Get-NetFirewallRule
  • Remove-NetFirewallRule
  • Rename-NetFirewallRule
  • Set-NetFirewallRule
  • Show-NetFirewallRule

Let’s take a look at a few simple examples of how to open ports in the Windows Firewall.

For example, if you want to allow incoming TCP connections on TCP ports 80 and 443 for both the Domain and Private profiles, run the following command:

New-NetFirewallRule -DisplayName 'HTTP-Inbound' -Profile @('Domain', 'Private') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('80', '443')

New-NetFirewallRule create new firewall rule with powershell

You can allow or block network access for a specific application (executable). For example, you may want to block outbound connections for the Firefox browser:

New-NetFirewallRule -Program “C:\Program Files (x86)\Mozilla Firefox\firefox.exe” -Action Block -Profile Domain, Private -DisplayName “Block Firefox browser” -Description “Block Firefox browser” -Direction Outbound

Let’s allow an incoming RDP connection on the default TCP\3389 port from only one IP address:

New-NetFirewallRule -DisplayName "AllowRDP" –RemoteAddress 192.168.2.200 -Direction Inbound -Protocol TCP –LocalPort 3389 -Action Allow

To allow ICMP pings for IP addresses from the specified ranges of IP addresses and subnets, create the following rule:

$ips = @("192.168.2.15-192.168.2.40", "192.168.100.15-192.168.100.200", ”10.1.0.0/16”)
New-NetFirewallRule -DisplayName "Allow inbound ICMPv4" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -RemoteAddress $ips -Action Allow
New-NetFirewallRule -DisplayName "Allow inbound ICMPv6" -Direction Inbound -Protocol ICMPv6 -IcmpType 8 -RemoteAddress $ips -Action Allow

Add a list of IP addresses from a plain text file to the firewall rule (one IP address per line):

$ips=Get-Content C:\temp\ip.txt
Get-NetFirewallrule -DisplayName 'AllowRDP'|Set-NetFirewallRule -RemoteAddress $ips

Allow all incoming connections from the specified IP address. This will add the IP address to the firewall whitelist:

$IP = '192.168.1.20'
New-NetFirewallRule -DisplayName "Allow $IP" -Direction Inbound -Action Allow -RemoteAddress $IP

Modifying an Existing Windows Firewall Rule Using PowerShell

If you want to edit a firewall rule, use the Set-NetFirewallRule cmdlet. For example, you may want to allow inbound connections from a specific IP address for a rule that you have previously created:

Get-NetFirewallrule -DisplayName 'HTTP-Inbound' | Get-NetFirewallAddressFilter | Set-NetFirewallAddressFilter -RemoteAddress 192.168.1.10

To add multiple IP addresses to a firewall rule, use the following PowerShell script:

$ips = @("192.168.2.15", "192.168.2.17",”192.168.100.15”)
$current_ips = (Get-NetFirewallRule -DisplayName 'HTTP-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$current_ips += $ips
Get-NetFirewallrule -DisplayName 'HTTP-Inbound'|Set-NetFirewallRule -RemoteAddress $current_ips

List of all IP addresses in a firewall rule:

Get-NetFirewallrule -DisplayName 'Http_inbound'|Get-NetFirewallAddressFilter

Remove one IP address from a firewall rule:

$removeip = "192.168.100.5"
$current_ips = (Get-NetFirewallRule -DisplayName 'HTTP-Inbound'| Get-NetFirewallAddressFilter).RemoteAddress
$filterIP = $current_ips | Where-Object{ $_ -notin $removeip }
Get-NetFirewallrule -DisplayName 'HTTP-Inbound'|Set-NetFirewallRule -RemoteAddress $filterIP

add ip address to existing firewall rule

How to Enable/Disable/Remove Windows Firewall Rule with PowerShell

You can use the Disable-NetFirewallRule and Enable-NetFirewallRule cmdlets to enable and disable firewall rules.

Disable-NetFirewallRule –DisplayName 'HTTP-Inbound'

To allow ICMP (ping), run this command:

Enable-NetFirewallRule -Name FPS-ICMP4-ERQ-In

To remove a firewall rule, use the Remove-NetFirewallRule cmdlet.

Remove-NetFirewallRule -DisplayName 'HTTP-Inbound'

To reset all Microsoft Firewall rules and restore the default settings, run the following command

netsh advfirewall reset

or:

(New-Object -ComObject HNetCfg.FwPolicy2).RestoreLocalFirewallDefaults()

This will delete all of the user-defined settings as well as the Microsoft Defender firewall rules. Only the network access rules that are built into Windows will remain.

Before resetting the firewall rules, you can export the current settings to a file.

netsh advfirewall export "C:\Backup\firewall-config.wfw"

Later, you can restore the old firewall settings by importing the rules file:

netsh advfirewall import "C:\Backup\firewall-config.wfw"

PowerShell: List Active Rules in Windows Firewall

The list of enabled firewall rules for incoming traffic can be displayed as follows

Get-NetFirewallRule | where {($_.enabled -eq $True) -and ($_.Direction -eq "Inbound")} |ft

You can only list outbound blocking rules:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound

If you want to display the program (executable) name in the rule:

Get-NetFirewallRule -Action Block -Enabled True -Direction Outbound | %{$_.Name; $_ | Get-NetFirewallApplicationFilter}

Get-NetFirewallrule - view firewall rule properties

As you can see, the Get-NetFirewallRule cmdlet doesn’t show network ports and IP addresses for firewall rules. To display the detailed information about allowed inbound (outbound) connections in a more convenient way with  the port numbers, use the following PowerShell script:

Get-NetFirewallRule -Action Allow -Enabled True -Direction Inbound |
Format-Table -Property Name,
@{Name='Protocol';Expression={($PSItem | Get-NetFirewallPortFilter).Protocol}},
@{Name='LocalPort';Expression={($PSItem | Get-NetFirewallPortFilter).LocalPort}},
@{Name='RemotePort';Expression={($PSItem | Get-NetFirewallPortFilter).RemotePort}},
@{Name='RemoteAddress';Expression={($PSItem | Get-NetFirewallAddressFilter).RemoteAddress}},
Enabled,Profile,Direction,Action

Use PowerShell to List Firewall Rules with port nubbers

PowerShell provides a wide range of options for managing Windows Firewall rules from the command prompt. You can automatically run PowerShell scripts to open/close ports if certain events happen. In the following article, we’ll look at simple PowerShell- and Windows Firewall-based solutions to automatically block RDP brute-force attacks on your Windows VDS host by adding the attacker’s IP address to the firewall rule.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Где искать папку windows old
  • Mediacreationtool windows 10 22h2
  • Как поменять диск загрузки в windows 10 в биос
  • Как открыть второе окно на компьютере windows 10
  • Vgn fz31zr драйвера windows 10