How to close TCP and UDP ports via windows command line

后端 未结 17 1653
忘掉有多难
忘掉有多难 2020-12-07 06:43

Does somebody knows how to close a TCP or UDP socket for a single connection via windows command line?

Googling about this, I saw some people asking the same thing.

17条回答
  •  孤街浪徒
    2020-12-07 07:40

    If you're runnning on Windows 8,`Windows Server 2012 or above with PowerShell v4 of above installed, you can use the below script. This finds the processes associated with the port & terminates them.

    Code

    #which port do you want to kill
    [int]$portOfInterest = 80
    
    #fetch the process ids related to this port
    [int[]]$processId = Get-NetTCPConnection -LocalPort $portOfInterest | 
        Select-Object -ExpandProperty OwningProcess -Unique | 
        Where-Object {$_ -gt 0} 
    
    #kill those processes
    Stop-Process -Id $processId 
    

    Documentation:

    • Get-NetTCPConnection - PowerShell's NetStat equivalent
    • Select-Object - Pull back specific properties from an object / remove duplicates
    • Where-Object - Filter values based on some condition
    • Stop-Process - PowerShell's TaskKill equivalent

提交回复
热议问题