Skip to content

Instantly share code, notes, and snippets.

@mikebeaton
Last active April 11, 2024 16:34
Show Gist options
  • Save mikebeaton/7e2c364e876c8d22e84e2456592d9d39 to your computer and use it in GitHub Desktop.
Save mikebeaton/7e2c364e876c8d22e84e2456592d9d39 to your computer and use it in GitHub Desktop.
Batch file to activate and restore an existing program if it exists, or start a new instance otherwise (in this case, Fork.exe)
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq Fork.exe" ^| find /I "Fork.exe"') do set pid=%%i
if "%pid%" == "" (
%localappdata%\Fork\Fork.exe
) else (
cscript //E:JScript //nologo "%~f0" "%~nx0" "%pid%"
)
exit /b %errorlevel%
endlocal
@if (@X)==(@Y) @end JScript comment */
var sh=new ActiveXObject("WScript.Shell");
if (sh.AppActivate(WScript.Arguments.Item(1)) == 0) {
sh.SendKeys("% r");
}
@KTibow
Copy link

KTibow commented Mar 24, 2021

Simpler version if you don't want all the features:

@if (@X)==(@Y) @end /*
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq Zoom.exe" ^| find /I "Zoom.exe"') do set pid=%%i
cscript //E:JScript //nologo "%~f0" "%~nx0" "%pid%"	
@if (@X)==(@Y) @end */ 

var sh=new ActiveXObject("WScript.Shell"); 
sh.AppActivate(WScript.Arguments.Item(1))

@mikebeaton
Copy link
Author

👍 ty

@haseakash
Copy link

haseakash commented Jun 1, 2021

How do i use this code for same batch which is running?

I don't want to call another batch file.

How to mix code ?

example

@if (@x)==(@y) @EnD /* JScript comment

@echo off
setlocal
for /f "tokens=2" %%i in ('tasklist /FI "IMAGENAME eq Fork.exe" ^| find /I "Fork.exe"') do set pid=%%i
if "%pid%" == "" (
%localappdata%\Fork\Fork.exe
) else (
cscript //E:JScript //nologo "%~f0" "%~nx0" "%pid%"
)
exit /b %errorlevel%
endlocal

@if (@x)==(@y) @EnD JScript comment */

var sh=new ActiveXObject("WScript.Shell");
if (sh.AppActivate(WScript.Arguments.Item(1)) == 0) {
sh.SendKeys("% r");
}

mybatch code ........

I'm getting error var not recognize, compilation error bla bla bla

share full working script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment