Stop Music Once Playing - windows

I am trying to get a song to play in the background of Windows, after a little looking I found this:
#echo off
set file=RRLJ.mp3
( echo Set Sound = CreateObject("WMPlayer.OCX.7"^)
echo Sound.URL = "%file%"
echo Sound.Controls.play
echo do while Sound.currentmedia.duration = 0
echo wscript.sleep 100
echo loop
echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000) >sound.vbs
start /min sound.vbs
This works well for starting the song but I have no way of stopping it from a .bat file. The only way I found to cut it short is to open task manager and close it from the processes.
I have tried:
taskkill /im wscript.exe
But I keep getting something in the window saying:
Success: Sent termination sidnal to the process "wscript.exe" with PID 185448
but the music continues to play until I manually end it with task manager

I'd use /T switch (Tree kill): terminates the specified process and any child processes which were started by it.
Here is a script to find ProcessID to terminate exactly needed process only using PID:
#ECHO OFF >NUL
for /F "usebackq tokens=*" %%G in (
`wmic process where "CommandLine like '%%sound.vbs%%' AND Caption like '%%script.exe%%'" get ProcessID/value ^|find /I "="`
) do (
rem echo %%G
for /F "tokens=2 delims==" %%H in ("%%~G") do echo taskkill /T /F /PID %%H
)
Note taskkill command is echoed merely... Remove echo when debugged.

This work for me, and is only one line.
Taskkill /IM "wscript.exe" /F>nul 2>&1

Related

How to kill same name processes by differing them by their parameter? in BATCH / .bat

Henlo smarter folks.
While having fun with automating some workflows [im doing this in batch (/ vba)], btw this means if you think its better / easier to perform this in vba hit me, i faced the problem of using taskkill for multiple processes of the same name.
First i tried to circumvent this by using their pids's, but i figured that this wont work because it changes everytime a process restarts, at least the ones i look for do.
In short:
When ive got two or more processes of the same name with parameters like
example.exe -test abcd and
example.exe -testing;
How to kill only the first one?
In long ... :
For example, if i would do:
taskkill /f /im example.exe this would crash or bsod the machine etc, or do;
taskkill /PID example_pid this would prompt an error not found or maybe even kill the wrong process
The full batch looks like this:
test_autokill.bat
:start
timeout 5
taskkill /f /im example1.exe
taskkill /f /im example2.exe
taskkill /f /im *and so on*
goto start
Additionally i guessed that i would have to use tasklist first to output processes including their parameters, but searching to do so failed completely.
Also i am not sure about what i would have to do next especially because i wasnt able to perform if+else (i think it usually said 'dont know what else is') conditions with tasklist previously.
Thanks for your knowledge
EDIT 1
I was pointed to a related Topic which wanted to do the "opposide" of. Tho i tried it without the "not" modidier.
All tries (below) replied the same error Message:
ERROR:
Description = The request is invalid.
My tries (in AdminCLI):
wmic Path win32_process Where "CommandLine Like 'C:\Windows\System32\svchost.exe -k NetworkService'" Call Terminate
wmic Path win32_process Where "CommandLine Like 'C:\Windows\System32\svchost.exe -k NetworkService'" Delete
wmic Path win32_process Where "CommandLine Like 'C:\Windows\System32\svchost.exe -k NetworkService' and name='svchost.exe'" Call Terminate
wmic Path win32_process Where "CommandLine Like 'C:\Windows\System32\svchost.exe -k NetworkService' and name='svchost.exe'" Delete
The original ones had a typo btw, scv instead of svc.
With a batch file, you can try like this way if you want to kill the first PID, you just remove the echo before the Taskkill command in this example :
#echo off
Set "WMIC_CMD=WMIC Process Where "CommandLine Like '%%-k NetworkService'" get Handle /Value"
SetLocal EnableDelayedExpansion
#for /f "tokens=1* delims==" %%I in ('%WMIC_CMD%') do (
#for /F "delims=" %%K in ("%%J") do (
Set /A Count+=1
set "Handle[!Count!]=%%K"
)
)
#for /L %%i in (1,1,%Count%) do (
echo %%i - !Handle[%%i]!
)
pause
REM IF You want to kill the first one
ECHO Taskkill /F /PID !Handle[1]!
pause
exit /b

Handle command response in windows bash

I'm writing a bash script that should restart a running process. I'm able to kill a process using the process name (pcm.exe). How ever, when i want to start the process, i want it to get the pcm.exe location from the earlier running process. This is because i don't know exactly where the program is located on different systems.
I have the following script:
wmic process where "name='pcm.exe'" get ExecutablePath /FORMAT:LIST
#taskkill /f /im pcm.exe >nul
#timeout /t 10 /nobreak >nul
#start h:/pandora/pcm.exe >nul
wmic successfully gets the PCM location:
ExecutablePath=H:\Pandora\PCM.exe
But how can i pass the response to a string and run #start (the path)?
TL;DR -
Use the set command
Details:
setlocal EnableDelayedExpansion
set "zTargetImage=notepad.exe"
set "zBinLocation=0"
for /f "skip=2 tokens=2 delims=," %%A in ('wmic process where "name='!zTargetImage!'" get ExecutablePath^,ThreadCount /format:csv 2^>^&1') do (
set "zBinLocation=%%A"
)
taskkill /f /im !zTargetImage! >nul 2>&1
timeout /t 2 /nobreak >nul
if not "!zBinLocation!"=="0" (
start "" "!zBinLocation!" >nul
)

PID lookup to recall and kill task

I'd like to create the below two separate lines of cmd script into a bat file. The PID changes so I'm having a hard time figuring out how to set this service PID to be dynamic.
Any help would be welcomed thank you!!
sc queryex DWDesktopService
taskkill /f /pid ####
You just need to scrape the PID value out of the sc output. It is awkward in cmd scripting. Change the service name to yours. When you are satisfied that the correct PID will be killed, remove the echo from the TASKKILL line.
FOR /F "usebackq delims=: tokens=1,2" %%a IN (`sc queryex "BITS" ^| FIND /I " PID "`) DO (
SET "PID=%%b"
)
echo TASKKILL /F /PID %PID%

How to fetch the pid and kill it using batch file?

i have to find a processid for a specific jar file and kill it using the same batch file.
C:\Users\k9>ps -ef|grep java
10892 5648 0 Mar 08 con 0:02 "C:\Program Files\Java\jdk1.7.0_51\bin\java" com.mkwebappserver.MainClass -app CATMkWebAppServerConsole\apps_list.html -autobui
13060 7828 0 09:42:28 con 49:05 java -Djsse.enableSNIExtension=false -Djava.util.logging.config.file=..\config\log.properties -classpath "../extlib/*";..\extlib\mysql-connector-
here i want to find pid of config\log.properties file and kill it using the batch file.
This is how I "find" and kill Adobe Acrobat
::Close acrobat and any opened PDF
taskkill /im acrobat.exe /t /f
timeout 2
/im for imagename, or program you're targeting
/t terminates the specified process and any child process which were started by it
/f Forcefully terminate the process
The most flexible way to detect a pid by its command line (where your jar should be included) is with wmic. To process the wmic result and assign it to a variable you'll need FOR /F :
#echo off
for /f "useback tokens=* delims=" %%# in (
`wmic process where "CommandLine like '%%my_jar.jar%%' and not CommandLine like '%%wmic%%' " get ProcessId /Format:Value`
) do (
for /f "tokens=* delims=" %%a in ("%%#") do set "%%a"
)
echo %processId%
echo taskkill /pid %processId% /f
Where you should change '%%my_jar.jar%%' with your jar name.To kill the process you'll have to delete the echo word in the last line. It is echoed in order to check if the correct process id is handled.
For more info:
WMIC
FOR /F
WQL
TASKKILL

how do I kill all cmd.exe except the one currently running from batch?

The past few days I have been working on a script that I thought would be rather easy but it seems not, and I do understand why. My problem is how to get around it.
The batch script I need explained:
I have a script that runs in cmd.exe that does a bunch of things like moving a huge amount of files from a location to another. Lets call it
movefile.cmd. This script works, but happens to stop sometimes (very rarely - lets not go into why and that script). Its important that this script always runs, so my idea here was to create a batch that exits cmd.exe and then re-opens the script each hour or so. Lets call this script restartcmd.bat
Sounds perfectly easy as I could do this:
#echo off
:loop
start c:\script\movefile.cmd
Timeout /nobreak /t 3600
Taskkill cmd.exe
goto loop
But obviously this doesn't work because my new script also runs in cmd.exe, so it would kill this process as well.
What I've tried:
So I made a copy of cmd.exe and renamed it into dontkillthis.exe. I run dontkillthis.exe and then open the restardcmd.bat from dontkillthis.exe - this works perfectly! But I need to be able to just dobbleclick my script instead of doing that. Why? Because its supposed to be as easy as possible and I want my restartcmd.bat to be in my startup folder.
I've been looking at the ideas of getting the exact process ID of cmd.exe and shutting that so that my dontkillthis.exe will remain, but I can't seem to nail it. Tried all thats written in here how to kill all batch files except the one currently running , but I can't get it to work.
I'm not sure if I'm being confused or if it actually is a bit hard to do this.
I'd really appreciate some help here.
Best Regards
MO
first you'll need the PID of the current CMD instance. The topic has been discussed here . I will offer you my solution - getCmdPID.bat
and here's the script (getCmdPID should in the same directory ):
#echo off
call getCmdPID
set "current_pid=%errorlevel%"
for /f "skip=3 tokens=2 delims= " %%a in ('tasklist /fi "imagename eq cmd.exe"') do (
if "%%a" neq "%current_pid%" (
TASKKILL /PID %%a /f >nul 2>nul
)
)
Normally with the following command I should be able to find the PID. Unfortunately this is not the case.
title exclude &tasklist /NH /v /fo csv /FI "WINDOWTITLE ne exclude*" /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"
So to achieve my goal, I used the following command:
FIND /I "exclude" 1>NUL
#echo off
TITLE exclude
(for /f "usebackq tokens=*" %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"`) do (
(
echo %%a | FIND /I "exclude" 1>NUL
) || (
for /f "usebackq tokens=2 delims=," %%i in (`echo %%a`) do (
echo TASKKILL /PID %%~i /f
)
)
)
)>_output-taskill.txt
TYPE _output-taskill.txt
Another approach to kill all the processes in a single line is to use filters on the command taskkill with filters should look like:
TASKKILL /F /FI "PID ne XXXX" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe
eq (equal)
ne (not equal)
gt (greater than)
lt (lesser than)
#echo off
TITLE exclude
(for /f "usebackq tokens=2 delims=," %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running" ^| FIND /I "exclude"`) do (
echo TASKKILL /F /FI "PID ne %%~a" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe
)
)>_output-taskill.txt
TYPE _output-taskill.txt
I have found a solution that utilizes text files to keep track of all previous PIDs the bat file has had. It attempts to kill them silently and then adds the current PID to the list after.
If you don't want it to kill the old, already existing process, simply replace the line that has "taskkill" with whatever you were wanting to do with it.
(might require you to run as admin in order to have permissions to kill the duplicate process. see permission elevation code below for optional implementation if you don't want to have to run as admin every time.)
#echo off
set WorkingDir=%cd%
if exist MostRecentPID.txt ( del "PIDinfo.txt" /f /q ) > nul
cd ..\..\..\..\..\..\..
title mycmd
tasklist /v /fo csv | findstr /i "mycmd" > %WorkingDir%\PIDinfo.txt
set /p PIDinfo=<%WorkingDir%\PIDinfo.txt
REM below, the 11 means get substring starting a position 11 with length of 5 characters. The tasklist command gives a long and verbose value so this will get just the PID part of the string.
set PID5chars=%PIDinfo:~11,5%
set PID4chars=%PIDinfo:~11,4%
if exist PreviousPIDs.txt (
for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
goto CheckIfFourCharPID
)
:CheckIfFourCharPID
if %PID4chars% gtr 8100 (
for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
echo %PID4chars% >> "PreviousPIDs.txt"
) else (
echo %PID5chars% >> "PreviousPIDs.txt"
)
Explanation: (warning: very technical)
-This solution gets a substring of the tasklist command to get just the PID. There will not be a PID for cmd.exe that is greater than 18100 so check if PID4chars is greater than 8100 so we know if it's a 4 digit or 5 digit number
case 1: a 5 digit PID like 17504 has a PID5chars val 17504 and a PID4chars val of 1750, so we add PID5chars to the text files of PIDs to kill
case 2: a 4 digit PID like 8205 has a PID5chars val of 8205" and a PID4chars val of 8205, so we add PID4chars to the text files of PIDs to kill
case 3: a 4 digit PID like 4352 has a PID5chars val of 4352" and a PID4chars val of 4352, so we add PID4chars to the text files of PIDs to kill
OPTIONAL PERMISSION ELEVATION CODE
(put this at the top of your bat file and it will auto-run it as admin.)
#echo off
setlocal DisableDelayedExpansion
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
cd ..\..\..\..\..\..\..\..
if exist %cd%\Temp (
set temp=%cd%\Temp
goto vbsGetPrivileges
)
if exist %cd%\Windows\Temp (
set temp=%cd%\Windows\Temp
goto vbsGetPrivileges
)
set temp=%cd%
:vbsGetPrivileges
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion
:CheckIfRunningAsAdmin
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
goto gotPrivileges
) else ( goto ElevatePermissions )
:ElevatePermissions
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
ECHO args = "ELEV " >> "%vbsGetPrivileges%"
ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
ECHO args = args ^& strArg ^& " " >> "%vbsGetPrivileges%"
ECHO Next >> "%vbsGetPrivileges%"
ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
"%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
exit /B
:gotPrivileges
setlocal & pushd .
cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
goto Continue
) else (
REM unable to elevate permissions so tell user to run file as admin manually
echo Please re-run this file as administrator. Press any key to exit...
pause > nul
goto Exit
)
:Continue
<insert rest of code here>
It would be much better to get the PID of your movefile.cmd. If you can edit it, add a title MyMoveFileProcess and get it's PID with
for /f "tokens=2" %%i in ('tasklist /v ^|find "MyMoveFileProcess"') do set PID=%%i
Then you can kill it with taskkill /pid %pid%
Instead of changing your movefile.cmd, you can also just start it with an title:
start "MyMoveFileProcess" c:\script\movefile.cmd
A couple of lines will help you achieve this:
TITLE exclude
taskkill /IM cmd.exe /FI "WINDOWTITLE ne exclude*"

Resources