通过从 .BAT 中查找正在使用的端口来终止进程 [英] Kill a Process by Looking up the Port being used by it from a .BAT

查看:27
本文介绍了通过从 .BAT 中查找正在使用的端口来终止进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 中,什么可以查找端口 8080 并尝试通过 .BAT 文件终止它正在使用的进程?

In Windows what can look for port 8080 and try to kill the process it is using through a .BAT file?

推荐答案

这是一个让你开始的命令:

Here's a command to get you started:

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P

当您对批处理文件有信心时,删除 @ECHO.

When you're confident in your batch file, remove @ECHO.

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P

请注意,您可能需要针对不同的操作系统稍微更改此设置.例如,在 Windows 7 上,您可能需要 tokens=5 而不是 tokens=4.

Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5 instead of tokens=4.

工作原理

FOR /F ... %variable IN ('command') DO otherCommand %variable...

这让您可以执行 command,并循环其输出.每一行都将被塞进%variable,并且可以在otherCommand 中任意扩展,随心所欲.%variable 在实际使用中只能有一个单字母的名字,例如%V.

This lets you execute command, and loop over its output. Each line will be stuffed into %variable, and can be expanded out in otherCommand as many times as you like, wherever you like. %variable in actual use can only have a single-letter name, e.g. %V.

"tokens=4 delims= "

这让你可以用空格分割每一行,并取该行中的第 4 个块,并将其填充到 %variable(在我们的例子中,%%P).delims 看起来是空的,但额外的空间实际上很重要.

This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -a -n -o

只需运行它并找出答案.根据命令行帮助,它显示所有连接和侦听端口."、以数字形式显示地址和端口号."和显示与每个连接关联的拥有进程ID.".我只是使用这些选项,因为其他人建议它,它碰巧工作:)

Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)

^|

这将获取第一个命令或程序 (netstat) 的输出并将其传递给第二个命令程序 (findstr).如果您直接在命令行上使用它,而不是在命令字符串中,您将使用 | 而不是 ^|.

This takes the output of the first command or program (netstat) and passes it onto a second command program (findstr). If you were using this directly on the command line, instead of inside a command string, you would use | instead of ^|.

findstr :8080

这会过滤任何传入它的输出,只返回包含 :8080 的行.

This filters any output that is passed into it, returning only lines that contain :8080.

TaskKill.exe /PID <value>

这会使用进程 ID 终止正在运行的任务.

This kills a running task, using the process ID.

%%P instead of %P

这在批处理文件中是必需的.如果您在命令提示符下执行此操作,则应改用 %P.

This is required in batch files. If you did this on the command prompt, you would use %P instead.

这篇关于通过从 .BAT 中查找正在使用的端口来终止进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆