如何使用 PowerShell 阻止 Windows 操作系统上的端口?
powershellmicrosoft technologiessoftware & coding更新于 2026/2/10 13:07:17
要在 Windows 操作系统上使用 PowerShell 阻止端口,我们需要使用 New-NetFirewallRule 命令更改防火墙设置。
示例
我们需要阻止计算机上的 5985 端口。以下代码将阻止本地计算机上 5985 端口上的所有 TCP 传入请求。
New-NetFirewallRule -DisplayName "Block WINRM HTTP Port" ` -Direction Inbound ` -LocalPort 5985 ` -Protocol TCP ` -Action Block
要阻止多个端口,我们只需要在 -LocalPort 参数中提供多个端口。
New-NetFirewallRule -DisplayName "Block WINRM HTTP/S Ports" ` -Direction Inbound ` -LocalPort 5985,5986 ` -Protocol TCP ` -Action Block
要阻止远程计算机上的端口,您可以使用 Invoke-Command cmdlet。请确保远程计算机可访问并能访问 WINRM 服务和端口。
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{
New-NetFirewallRule -DisplayName "Block web ports" `
-Direction Outbound `
-LocalPort 80,8080 `
-Protocol TCP `
-Action Block
}

