Reputation: 69
I have been using the following script to check if a particular named window is open.
I got it from this thread:-
How do you test if a window (by title) is already open from the command prompt?
ideally I will expand the else part to close the window if it is found to be open.
@For /f "Delims=:" %A in ('tasklist /v /fi "WINDOWTITLE eq test.bat - Notepad"') do @if %A==INFO (echo Prog not running) else SET "BREX=Awesome" &echo %BREX%
Unfortunately when I run this script it returns three instances of my else string?
Is there any way to reduce this down to returning one instance?
Upvotes: 2
Views: 4379
Reputation: 14290
If you really want to do this with one line from the cmd prompt you can do this.
cmd /v:on /c "@For /f "Delims=:" %A in ('tasklist /v /nh /fi "WINDOWTITLE eq test.bat - Notepad"') do @if %A==INFO (echo Prog not running) else (SET "BREX=Awesome") &echo !BREX!"
Or use some conditional execution.
tasklist /v /nh /fi "WINDOWTITLE eq test.bat - Notepad" |findstr /B /C:"INFO: No tasks are running">nul && (echo Program not running) || (echo Awesome)
Upvotes: 1
Reputation: 4506
You could use findstr
instead. You're getting multiple lines of output as you're looping over each line of output
tasklist /v /fi "WINDOWTITLE eq test.bat - Notepad" | findstr /C:"No tasks are running"
if %errorlevel% NEQ 0 (
echo awesome
) else (
echo Prog not running
)
Upvotes: 2