You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用New-NetFirewallRule创建规则后,如何获取LocalPort值?

获取新建Windows防火墙规则的LocalPort值

方法一:通过规则ID关联端口筛选器

New-NetFirewallRule返回的规则对象包含唯一的Name(规则ID),利用这个ID可以关联到对应的端口筛选器,从而提取LocalPort:

# 创建规则并保存返回结果
$newRule = New-NetFirewallRule -DisplayName "Allow debug rule" -Direction inbound -Profile Any -Action Allow -LocalPort 3333 -Protocol UDP -RemoteAddress 127.0.0.2

# 通过规则对象获取关联的端口筛选器,提取LocalPort
Get-NetFirewallPortFilter -AssociatedNetFirewallRule $newRule | Select-Object LocalPort

执行结果示例:

LocalPort
---------
3333

方法二:提前保存端口参数(简单直接)

如果只是需要记录创建规则时使用的端口值,可在执行命令前将端口存入变量,后续直接调用:

$targetPort = 3333
$newRule = New-NetFirewallRule -DisplayName "Allow debug rule" -Direction inbound -Profile Any -Action Allow -LocalPort $targetPort -Protocol UDP -RemoteAddress 127.0.0.2

# 直接输出端口值
Write-Host "新建规则的本地端口为: $targetPort"

为什么直接筛选返回对象拿不到LocalPort?

New-NetFirewallRule返回的是防火墙规则的基础配置对象,端口、远程地址这类筛选条件属于独立的筛选器组件,需要通过专门的Get-NetFirewallPortFilter、Get-NetFirewallAddressFilter命令去获取对应属性。

内容的提问来源于stack exchange,提问作者AntonioK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:12:34