我正在处理一个cmd脚本,希望在任务列表中找到一些进程。所以我得到的是一个类似"prog=devcpp.exe,prog1=notepad.exe...“的数组。并找到我用于命令的这些进程。好的,但是当我执行"tasklist /fi“命令时,它似乎无法识别数组,并且没有给出预期的结果。
代码是:
set prog[0]=devcpp.exe
set prog[1]=notepad.exe
set prog[2]=calc.exe
FOR /l %%a IN (0,1,2) DO (
tasklist /fi "IMAGENAME eq %prog[%%a]%"
)但结果是:
error: the search filter cannot be recognized当然,我正在运行这些进程...那么,有什么建议吗?
发布于 2021-11-12 22:12:56
首先,删除prog[2]设置中的尾随引号字符。
其次,在调用tasklist时,必须将百分号字符加倍才能保留1。并且,使用命令行解释器。%ComSpec%,用于解释变量。
set prog[0]=devcpp.exe
set prog[1]=notepad.exe
set prog[2]=powershell.exe
FOR /l %%a IN (0,1,2) DO (
"%ComSpec%" /C tasklist /fi "IMAGENAME eq %%prog[%%a]%%"
)对于最终目标是什么,您没有给出任何线索。按照@Bill_Stewart的建议,用PowerShell编写代码可能会更容易。
发布于 2021-11-13 20:06:12
以下是我对此任务的建议,其中包含一个带注释的批处理文件。
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Delete all environment variables of which name starts with prog[.
for /F "delims==" %%I in ('set prog[ 2^>nul') do set "%%I="
rem Define environment variables with the executables to get listed.
set "prog[0]=devcpp.exe"
set "prog[1]=notepad.exe"
set "prog[2]=calc.exe"
rem Run TASKLIST in a loop to get output a list of those processes
rem from the list defined above which are currently running with the
rem header output on English Windows just on first running process.
set "Header=1"
for /F "tokens=1* delims==" %%I in ('set prog[') do if defined Header (
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq %%J" 2>&1 | %SystemRoot%\System32\findstr.exe /B /I /L /V /C:"INFO:"
if not errorlevel 1 set "Header="
) else (
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq %%J" 2>nul
)
endlocal要了解使用的命令及其工作原理,请打开一个command prompt窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。
echo /?endlocal /?findstr /?for /?if /?rem /?set /?setlocal /?tasklist /?https://stackoverflow.com/questions/69949046
复制相似问题