How to block ports on the Windows Operating System using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To block the port using PowerShell on the Windows OS, we need to change the firewall settings using the New-NetFirewallRule command.


We need to block the port 5985 on the computer. The below code will block all TCP Incoming requests on the 5985 port on the local computer.

New-NetFirewallRule -DisplayName "Block WINRM HTTP Port" `
                    -Direction Inbound `
                    -LocalPort 5985 `
                    -Protocol TCP `
                    -Action Block

To block the multiple ports we just need to provide multiple ports in -LocalPort parameter.

New-NetFirewallRule -DisplayName "Block WINRM HTTP/S Ports" `
                    -Direction Inbound `
                    -LocalPort 5985,5986 `
                    -Protocol TCP `
                    -Action Block

To block ports on the remote computers, you can use the Invoke-Command cmdlet. Make sure the remote computer is reachable and can access the WINRM service and port.

Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{
    New-NetFirewallRule -DisplayName "Block web ports" `
    -Direction Outbound `
    -LocalPort 80,8080 `
    -Protocol TCP `
    -Action Block
Updated on 16-Oct-2020 09:39:26