# 获取动态IP地址 $dynamicIp = ([System.Net.Dns]::GetHostAddresses("你的动态域名.com")).IPAddressToString# 定义端口列表 $ports = @(8877, 8899)foreach ($port in $ports) {$ruleName = "AllowPort$port"# 检查规则是否存在,如果不存在则创建规则if (-not (Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue)) {New-NetFirewallRule -DisplayName $ruleName -Direction Inbound -Protocol TCP -LocalPort $port -Action Allow}# 更新防火墙规则,允许指定动态IP访问指定端口Set-NetFirewallRule -DisplayName $ruleName -RemoteAddress $dynamicIp -Direction Inbound -Protocol TCP -LocalPort $port }
保存上述代码为UpdateFirewallIP.ps1
然后创建Windows计划任务,设置每小时运行一次。