在 Windows 防火墙开放端口(New-NetFirewallRule)

用一条 PowerShell cmdlet 为 TCP/UDP 端口创建入站放行规则,之后也能干净地删除。

Windows端口PowerShell防火墙中风险
运行 New-NetFirewallRule -DisplayName "Allow HTTP 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow 即可开放该端口。

01命令

命令
$ New-NetFirewallRule -DisplayName "Allow HTTP 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow

02作用说明

与读取规则相对,创建规则是 NetSecurity 模块的另一半功能,而且支持精细化限定:-RemoteAddress、-Profile(Domain/Private/Public)和 -Program 可以把规则收得比图形界面里通常配置的更窄。撤销用同名 DisplayName 的 Remove-NetFirewallRule,或用 Disable-NetFirewallRule 保留规则但暂时关闭。这样创建的规则会正常出现在“高级安全 Windows Defender 防火墙”里。

03风险

风险中风险
使用条件Run PowerShell as Administrator
!注意: 每个开放的入站端口都是攻击面——如果服务不打算公开,尽量用 -Profile 和 -RemoteAddress 限定范围,而不是全开放行。

04撤销

撤销
$ Remove-NetFirewallRule -DisplayName "Allow HTTP 8080"

05来源

  • New-NetFirewallRule | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents New-NetFirewallRule with parameters -Direction, -Protocol, -LocalPort and -Action to create an inbound allow rule.

最后验证: 2026-09-17 · 分类: 网络

06相关方案