从 Windows 批处理脚本中的文件中读取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/298292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:37:26  来源:igfitidea点击:

Reading a value from a file in a windows batch script

windowsfilescriptingbatch-file

提问by Harry Lime

I'm trying to read a value from a file and use it in a subsequent command.

我正在尝试从文件中读取值并在后续命令中使用它。

I have a file called AppServer.pidwhich contains the process id of my app server (just the number, it's not a properties file or anything like that).

我有一个名为的文件AppServer.pid,其中包含我的应用程序服务器的进程 ID(只是数字,它不是属性文件或类似的东西)。

The app server is hanging, so I want to take this value and pass it to the kill command. So my script will be something like

应用服务器挂了,所以我想把这个值传给kill命令。所以我的脚本将类似于

SET VALUE_FROM_FILE=AppServer.pid # or something
taskkill /pid %VALUE_FROM_FILE% /f

Is there a convenient way to do this in Windows scripting?

在 Windows 脚本中是否有一种方便的方法可以做到这一点?

回答by Cocowalla

This works:

这有效:

SET /P VALUE_FROM_FILE= < AppServer.pid
taskkill /pid %VALUE_FROM_FILE% /f

The /P parameter used with SET allows you to set the value of a parameter using input from the user (or in this case, input from a file)

与 SET 一起使用的 /P 参数允许您使用来自用户的输入(或者在这种情况下,从文件输入)来设置参数的值

回答by RuntimeException

for /f %%G in (appid.txt) do (SET PID=%%G)
echo %PID%
taskkill etc here... 

This might help !

这可能会有所帮助!

回答by isapir

If you know the name of the process, as returned from the command tasklist, then you can run taskkillwith a filter on the process name, i.e. /FI IMAGENAME eq %process_name%.

如果您知道从 command 返回的进程名称,tasklist那么您可以taskkill在进程名称上使用过滤器运行,即/FI IMAGENAME eq %process_name%.

For example, to kill all of the processes named nginx.exerun:

例如,要杀死所有名为nginx.exerun的进程:

    taskkill /F /FI "IMAGENAME eq nginx.exe"

Which "reads in English": kill all tasks (forcefully if needed via /F) that match the filter /FI"IMAGENAME equals nginx.exe".

其中“以英语读取”:杀死/F与过滤器/FI“IMAGENAME equals nginx.exe”匹配的所有任务(如果需要,强制通过)。