I am going over this process many times. I have to kill a process on a Windows machine and I just know its port.
Normally the steps are as below: Find the PID by looking at the ports (example port 8084) List the processes running on ports
netstat -a -o -n
And then kill the process on that port with the following command
taskkill /F /PID <pid>
Is there any thing like a pipe or similar that I can use on Windows OS to run this command in one line!?
Best Answer
Both
cmd.exe
and PowerShell support pipes from one command to another. In PowerShell something like (this should be on a single line on the command line, or use ` to escapte newlines in a script):Where:
Select -skip 4
skips the first four header lines. (Select
is short forSelect-Object
used to perform SQL SELECT like projects of objects.%
is short forForeach-Object
which performs a script block on each object ($_
) in the pipeline and outputs the results of the script block to the pipeline. Here it is first breaking up the input into an array of fields and then creating a fresh object with two propertiesOriginal
the string fromnetstat
andFields
the array just created.?
is short forWhere-Object
which filters based on the result of a script block. Here matching a regex at the end of the second field (all PowerShell containers a zero based).(All tested except the last element: I don't want to start killing processes :-)).
In practice I would simplify this, eg. returning just 0 or the PID from the first
foreach
(which would be designed to ignore the headers) and filter on value not zero before callingtaskkill
. This would be quicker to type but harder to follow without knowing PowerShell.