[英]batch file wmic usage
I need to get pid
from below command which works if I use it in command line like below:如果我在命令行中使用它,我需要从下面的命令中获取
pid
,如下所示:
wmic process where "name="java.exe" and CommandLine like '%%cassandra%%'" get ProcessId | FINDSTR /v ProcessId | FINDSTR /r /v "^$"
but fails if used in .bat file:但如果在 .bat 文件中使用则会失败:
FOR /F "tokens=2" %%G IN ('wmic process where ^(name^="java.exe"^ and CommandLine like '%%cassandra%%') get ProcessId ^| FINDSTR /v ProcessId ^| FINDSTR /r /v "^$"') DO (
set PARENT_PID=%%G
)
echo !PARENT_PID!
Can anyone help in this?任何人都可以帮忙吗?
Your escape points are incorrect and not sure if you enabled delayedexpansion
, but I will not be using it in this example:你的转义点不正确,不确定你是否启用了
delayedexpansion
,但我不会在这个例子中使用它:
@echo off
for /F "tokens=2 delims==" %%G IN ('wmic process where (name^="java.exe" and commandline like '%%cassandra%%'^) get ProcessId /value') DO if not defined parent_pid set "parent_pid=%%G"
echo %parent_pid%
You will note that I used the /value
switch for wmic
and removed the findstr /v
command, because I am using =
as delimiter for splitting the value.您会注意到我为
wmic
使用了/value
开关并删除了findstr /v
命令,因为我使用=
作为分割值的分隔符。
Also note, if you have more than one process running with the same commandline and name, you will only get one result, because you only set a value once, so in that case, do not set a variable.另请注意,如果您有多个进程使用相同的命令行和名称运行,您只会得到一个结果,因为您只设置了一次值,因此在这种情况下,不要设置变量。 ie:
IE:
@echo off
for /F "tokens=2 delims==" %%G IN ('wmic process where (name^="java.exe" and commandline like '%%cassandra%%'^) get ProcessId /value') DO echo %%G
The code you use within the for /F
loop is not the same as the one you tried in Command Prompt as there are additional parentheses.您在
for /F
循环中使用的代码与您在命令提示符中尝试的代码不同,因为有额外的括号。 Then you are escaping the opening (
but forgot the closing )
, which is more important as it ends the parenthesised block behind the in
keyword.然后你正在逃避开头
(
但忘记了结尾)
,这更重要,因为它结束了in
关键字后面的括号块。
Anyway, you should change the wmic
command line and quote the whole where
clause:无论如何,您应该更改
wmic
命令行并引用整个where
子句:
wmic Process where "Name='java.exe' and CommandLine like '%%cassandra%%'" get ProcessId
So you do not have to bother to build escape sequences when using this inside of for /F
:因此,在
for /F
内部使用它时,您不必费心构建转义序列:
set "PARENT_PID="
for /F "skip=1 delims=" %%P in ('
wmic Process where "Name='java.exe' and CommandLine like '%%cassandra%%'" get ProcessId
') do for /F "tokens=1" %%Q in ("%%P") do set "PARENT_PID=%%Q"
echo/%PARENT_PID%
The second for /F
loop is used to remove arefacts (orphaned carriage-return characters) coming from the Unicode-to-ASCII/ANSI conversion of the wmic
command by for /F
.第二个
for /F
循环用于删除来自for /F
的wmic
命令的 Unicode 到 ASCII/ANSI 转换的事实(孤立的回车字符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.