Close All Program Except these with CMD - batch-file

i have this code :
This is a batch file code
#echo off
title Kill all running apps - Bharat Balegere - AgniPulse.com
cd c:\windows\System32
for /f "skip=3 tokens=1" %%i in ('TASKLIST /FI "USERNAME eq %userdomain%\%username%" /FI "STATUS eq running"') do (
if not "%%i"=="svchost.exe" (
if not "%%i"=="explorer.exe" (
if not "%%i"=="cmd.exe" (
if not "%%i"=="tasklist.exe" (
echo.
taskkill /f /im "%%i"
echo.
)
)
)
)
)
pause
but it will close all of the program
i try to edit it and add something like this if not "%%i"=="notepad.exe" (
but its not working anyway and when i click on batch file its nothing
so i don't know how to edit this
and put some except on it!
thanks in advance

You can give a try for this batch file with a whitelist for killing process
Of course you can modify your whitelist variable as you need :
#echo off
Title Kill all running apps - Bharat Balegere - AgniPulse.com
set "whitelist=avast mbam dllhost conhost"
Set "whitelist=%whitelist% taskeng skype"
Set "whitelist=%whitelist% firefox explorer cmd"
Set "whitelist=%whitelist% chrome tasklist taskmgr notepad"
#For /f "skip=3 tokens=1" %%i in (
'TASKLIST /FI "USERNAME eq %userdomain%\%username%" /FI "STATUS eq running" ^| findstr /VI "%whitelist%"'
) Do (
echo Taskkill /IM "%%i" /F
)
pause & exit
You can of course remove the echo command if that you want this list to be killed !
EDIT :
And here is another batch with whitelist using WMIC
#echo off
Title Process killer with a white list
Mode con cols=50 lines=40 & color 9B
setlocal
Set "White_Process_List=%~dpn0_White_Process_List.txt"
set "Ignoring_Process_List=%~dpn0_Ignoring_Process_List.txt"
set "Terimnated_Process_List=%~dpn0_Terimnated_List.txt"
If exist "%Ignoring_Process_List%" Del "%Ignoring_Process_List%"
If exist "%Terimnated_Process_List%" Del "%Terimnated_Process_List%"
:Whitelist
set "whitelist=Microsoft Mozilla Google Avast Panda ESET Kaspersky Avira AVG Bitdefender Malwarebytes Norton McAfee GAS IBM Skype"
If not exist "%White_Process_List%" echo %whitelist% > "%White_Process_List%"
Set /p whitelist=<"%White_Process_List%"
:Analyze
for /f "tokens=2 delims=," %%I in (
'wmic process get executablepath^,status /format:csv ^| find "\"'
) do (
set "proc=%%~I"
setlocal enabledelayedexpansion
wmic datafile where "name='!proc:\=\\!'" get manufacturer 2>nul | findstr /i "%whitelist%" >nul && (
( echo Ignoring : %%~nxI & echo "%%~I"
echo --------------------------------------- )>>!Ignoring_Process_List! 2>&1
) || (
( echo Terminating: %%~nxI )>con
( echo Terminating : %%~nxI & echo "%%~I"
Taskkill /im "%%~nxI" /f /t
echo --------------------------------------- )>>!Terimnated_Process_List! 2>&1
)
endlocal
)
Timeout /T 2 /nobreak>nul

Related

How to record the count of a TaskList

I have a process called "Ulti.exe". Due to my project requirements I have more than one copy of it running at any one time. If the number of copies of "Ulti.exe" drop below 3, I need to kill all the processes and restart them again.
How can I save the TaskList count into a variable? Currently, the following command:
TaskList | FIND /C "Ulti.exe"
if typed into cmd.exe returns me the number of "Ulti.exe" processes accurately. How can I incorporate this into a .bat file so I can use this number as a variable?
Get the output of a command with a for /f loop:
for /f %%a in ('TaskList ^| FIND /I /C "Ulti.exe"') do set count=%%a
echo %count%
While counting you can as well gather the PIDs to ease killing them if needed
:: Q:\Test\2018\11\02\SO_53115422.cmd
#Echo off & SetLocal EnableExtensions EnableDelayedExpansion
Set "Prog=Ulti.exe"
::Set "Prog=firefox.exe"
Set "Count="
Set "PIDs="
for /f "tokens=2" %%A in (
'TaskList /FI "IMAGENAME eq %Prog%" ^| Findstr /i "%Prog%"'
) do (
Set /A Count+=1
Set PIDs=!PIDs! /PID %%A
)
If defined Count (
If !Count! lss 3 (
echo taskkill %PIDs%
echo restart %Prog%
) else (
echo %Prog% running %Count% times [%PIDs%]
)
) else (
Echo %Prog% not running
Echo start %Prog%
)
Sample output:
> SO_53115422
Ulti.exe running 5 times [ /PID 3664 /PID 10332 /PID 3544 /PID 8996 /PID 11192]
> SO_53115422
Ulti.exe not running
start Ulti.exe
> SO_53115422
taskkill /PID 8056 /PID 2704
restart Ulti.exe
The taskkill command is only echoed while testing

Formatting results in .CMD

I am attempting to create a basic script that runs and checks for basic system info but I want the output to be formatted so the results are on the same line and easily readable.
#Echo Off
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
wmic cpu get name, status
systeminfo | findstr /C:"Total Physical Memory"
#echo off & setlocal ENABLEDELAYEDEXPANSION
SET "volume=C:"
FOR /f "tokens=1*delims=:" %%i IN ('fsutil volume diskfree %volume%') DO (
SET "diskfree=!disktotal!"
SET "disktotal=!diskavail!"
SET "diskavail=%%j"
)
FOR /f "tokens=1,2" %%i IN ("%disktotal% %diskavail%") DO SET "disktotal=%%i"& SET "diskavail=%%j"
ECHO(Total Space: %disktotal:~0,-9% GB
ECHO(Available Space: %diskavail:~0,-9% GB
systeminfo | find "System Boot Time:"
systeminfo | find "System Type:"
Echo Antivirus: & wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName | findstr /V /B /C:displayName || echo No Antivirus installed
The main example of this would be the wmic command placing the result on the next line rather than the same line.
Also any tips of better ways of scripting what I currently have would be appreciated.
#echo off
setlocal
for /f "tokens=1,* delims=:" %%A in ('systeminfo') do (
if "%%~A" == "OS Name" (
call :print "%%~A" %%B
) else if "%%~A" == "OS Version" (
call :print "%%~A" %%B
call :cpu
) else if "%%~A" == "Total Physical Memory" (
call :print "%%~A" %%B
call :fsutil C:
) else if "%%~A" == "System Boot Time" (
call :print "%%~A" %%B
) else if "%%~A" == "System Type" (
call :print "%%~A" %%B
)
)
:next
call :antivirus
pause
exit /b
:print
setlocal enabledelayedexpansion
set "name=%~1"
if not defined name exit /b
set "name=%~1 "
set "full=%*"
set "full=!full:,=!"
set "data="
set "skip1="
for %%A in (!full!) do (
if not defined skip1 (
set "skip1=defined"
) else if not defined data (
set "data=%%~A"
) else (
set "data=!data! %%~A"
)
)
echo !name:~,30!: !data!
exit /b
:antivirus
setlocal enabledelayedexpansion
set "antivirus="
for /f "tokens=*" %%A in ('
2^>nul wmic /node:localhost
/namespace:\\root\SecurityCenter2 path AntiVirusProduct
Get DisplayName /value
^| findstr /i /b /c:"DisplayName" ^|^| echo No Antivirus installed
') do set "antivirus=%%~A"
if /i "!antivirus:~,12!" == "DisplayName=" set "antivirus=!antivirus:~12!"
call :print Antivirus "!antivirus!"
exit /b
:cpu
for /f "tokens=1,* delims==" %%A in ('wmic cpu get name^, status /value') do (
call :print "%%~A" %%B
)
exit /b
:fsutil
setlocal enabledelayedexpansion
2>nul >nul net session || exit /b
for /f "tokens=1,* delims=:" %%A in ('2^>nul fsutil volume diskfree %1') do (
set "name=%%~A"
set "value=%%~B"
call :print "!name:bytes=GBs!" !value:~,-9!
)
exit /b
The fsutil command outputs alittle different.
I chose an easy option if it is OK.
Unsure of antivirus output as you need both results of
installed or not to be sure.
It only runs systeminfo once to save time.
Look at set /? for information about substitution that
is used.
The net session command is used to test if script is run as Admin.
If not Admin, then fsutil will be skipped as it requires Admin.
Look at for /? for usage of the command that is used in the script.
Use of enabledelayedexpansion is used to prevent special
characters being exposed which may cause error otherwise.
And used in code blocks to delay expansion as needed.
Remove comma from value strings which get replaced with a space.
A comma is often used as thousands separator and numbers look odd
with a space instead. This occurs because of usage of a simple
for loop interpreting comma as a argument separator. Some other
chararters may also do this though perhaps a space maybe better
than none in their case.
The output of WMIC is unicode !
The trailing <CR> can be removed by passing the value through another FOR /F loop. This also removes the phantom "blank" line (actually a <CR>)
#Echo Off
Call :GET_CPU name CPU_Name
Set "WMIC_Antivirus=wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName ^| findstr /V /B /C:displayName"
#For /F "delims=" %%I in ('%WMIC_Antivirus%') do (
for /f "delims=" %%A IN ("%%I") DO SET "Antivirus=%%A"
)
echo CPU : %CPU_Name%
echo Antivirus : %Antivirus%
pause & exit
::----------------------------------------------------
:GET_CPU
Set "WMIC_CPU=wmic cpu get name /Value"
FOR /F "tokens=2 delims==" %%I IN (
'%WMIC_CPU% ^| find /I "%~1" 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::----------------------------------------------------
You can try to save the output into a text file :
#Echo Off
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO **************************************
ECHO Running Admin shell... Please wait...
ECHO **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
SetLocal EnableDelayedExpansion
set "Log=%~dp0Log.txt"
If exist "%Log%" Del "%Log%"
Call :GET_CPU name CPU_Name
Set "WMIC_Antivirus=wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName ^| findstr /V /B /C:displayName"
#For /F "delims=" %%I in ('%WMIC_Antivirus%') do (
for /f "delims=" %%A IN ("%%I") DO SET "Antivirus=%%A"
)
(
Echo.
Echo ***************************** General infos ***********************************
Echo.
Echo Running under: %username% on profile: %userprofile%
Echo Computer name: %computername%
Echo.
systeminfo
Echo Operating System:
Echo PROCESSOR ARCHITECTURE : %PROCESSOR_ARCHITECTURE%
echo NUMBER_OF_PROCESSORS : %NUMBER_OF_PROCESSORS%
echo PROCESSOR_IDENTIFIER : %PROCESSOR_IDENTIFIER%
echo PROCESSOR_LEVEL : %PROCESSOR_LEVEL%
echo PROCESSOR_REVISION : %PROCESSOR_REVISION%
echo OS TYPE : %OS%
echo(
echo Program files path : %Programfiles%
echo Program files(86^) path : %Programfiles(86^)%
echo ProgramW6432 path : %ProgramW6432%
echo PSModulePath : %PSModulePath%
echo SystemRoot : %SystemRoot%
echo Temp Folder : %Temp%
echo CPU : !CPU_Name!
echo Antivirus : !Antivirus!
Echo.
Echo **************************** Drives infos *************************************
Echo.
Echo Listing currently attached drives:
wmic logicaldisk get caption,description,volumename | find /v ""
Echo.
Echo Physical drives information:
for /F "tokens=1-3" %%A in ('fltmc volumes^|find ":"') do echo %%A %%B %%C
)>>"%Log%"
Start "" "%Log%" & exit
::----------------------------------------------------
:GET_CPU
Set "WMIC_CPU=wmic cpu get name /Value"
FOR /F "tokens=2 delims==" %%I IN (
'%WMIC_CPU% ^| find /I "%~1" 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::----------------------------------------------------

Stop Music Once Playing In Background PC

Im making a cool hidden folder passworded USB drive. I have a little image that opens and I want to play music using this code.
set "file=music.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
I want to end the music after the user types the password. Or just the ability to tell it to stop.
I found in another post on here a solution by a user but he doesnt explain how to use it. Here is the link to that post. Link to the post Im new to batch so just giving me a script wont help I kind of need to know how to use it.
This is the script I dont understand how to use that will stop the music. According to the post I linked.
#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
)
Here is the password code im using.
#echo off
set pass= 123abc
echo Enter Password
set /p ui=
if %ui%==%pass% (goto open)
echo Wrong Password
pause
exit
:open
start folder
How to stop the music
Note taskkill command is echoed merely... Remove echo when debugged.
see instruction by #JosefZ here : https://stackoverflow.com/a/29271203/9222942
remove the 'echo' word from this line :
for /F "tokens=2 delims==" %%H in ("%%~G") do echo taskkill /T /F /PID
will becomes :
for /F "tokens=2 delims==" %%H in ("%%~G") do taskkill /T /F /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
)

How to Detect Multiple Monitors in a Batch File

I have recently started diving into writing Batch files and I have a question. I'm trying to create a file that checks to see if my secondary monitor is connected and than if it is switches the primary display to the secondary screen. (Yes I do know about the windows+P shortcut)...
So far I have figured out that "DisplaySwitch.exe /external" sets the default display to the secondary monitor but I cannot find out how to detect whether the display is there first.
-Cheers, Luke
With Windows 10, may be just a call to:
wmic desktopmonitor get DeviceID
output:
DeviceID
DesktopMonitor1
DesktopMonitor2
More details about monitor with :
wmic desktopmonitor get
By calling a powershell from the cmd the following will get the number of monitors:
powershell -Command "exit (Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams | Select-String -Pattern 'InstanceName').length"
set nMons=%ERRORLEVEL%
One possible way is to use dxdiag though it is not the fastest way:
#echo off
del ~.txt /q /f >nul 2>nul
dxdiag /t ~
w32tm /stripchart /computer:localhost /period:1 /dataonly /samples:3 >nul 2>&1
setlocal enableDelayedExpansion
set currmon=1
for /f "tokens=2 delims=:" %%a in ('find "Current Mode:" ~.txt') do (
echo Monitor !currmon! : %%a
set /a currmon=currmon+1
)
endlocal
del ~.txt /q /f >nul 2>nul
this will print the resolutions of all monitors.
Update:
dxdiag prints info about all monitors so you can check if there are more than one monitors:
#echo off
del ~.txt /q /f >nul 2>nul
start "" /w dxdiag /t ~
for /f "tokens=1* delims=:" %%a in ('find /c "Current Mode:" "~.txt"') do (
set /a "number_of_monitors=%%b"
rem echo #%%b#
)
rem exit /b 0
echo %number_of_monitors%
rem :---- if it needed -----:
if defined number_of_monitors ( if %number_of_monitors% GTR 1 ( echo second monitor connected ) else (echo only one monitor connected ))
del ~.txt /q /f >nul 2>nul
#npocmaka's answer didn't quite work for me, but this variation of his code did (Windows 10):
rem #echo off
del %TEMP%\dxdiag.txt /q /f >nul 2>nul
start "" /w dxdiag -64bit -t %TEMP%\dxdiag.txt
for /f "tokens=3" %%f in ('find /c"Monitor Name:" %TEMP%\dxdiag.txt') do set MONITOR_COUNT=%%f
if defined MONITOR_COUNT ( if %MONITOR_COUNT% GTR 1 ( echo second monitor connected ) else (echo only one monitor connected ))
del %TEMP%\monitors.txt /q /f >nul 2>nul
SET monitors=monitors.txt
SET nMons=0
MultiMonitorTool.exe /scomma "%monitors%"
FOR /F "skip=1 tokens=9 delims=," %%a IN (%monitors%) DO IF %%a GTR 0 SET /A nMons += 1
echo Number of monitors: %nMons%
MultiMonitorTool
Here is quick way to get connected monitors count via powershell
$m = Get-PnpDevice -Class Monitor -Status OK | measure; $m.Count

taskkill for particular user

how can i kill multiple task of same user we are using this two codes
Code no1
#ECHO OFF
TASKKILL /F /IM explorer.exe
cls
Echo "Please Specify the User ID"
Set /p u=
set USER=%u%#%userdomain%
Echo "Please Specify the PASSWORD"
runas /user:%USER% Explorer.exe
cls
echo "Press any key to Switch Back to Default USer Profile"
Pause
Echo "please enter your password again for verification"
runas /user:%USER% C:\switch.bat
pause
cls
start %windir%\explorer.exe
exit
Code no2 (this File name Switch.bat)
#echo off
TASKKILL /F /IM Explorer.exe
exit
Actually the general idea behind to create this it switches in win XP like win 7 without logging off
Issue is when it switch back to original profile
all the task of the second user doesnt stop
is that any way to stop all task for a specific user which are running
you can try with tskill . It can kill a process and accepts as parameter the user ID:
Kill explorer for the same user
setlocal enabledelayedexpansion
set exe_name=Explorer
for /f "skip=1 tokens=1,2,3" %%S in ('query user') do (
set "current_user=%%S"
if "!current_user:~0,1!" EQU ">" (
for /f "tokens=2 delims= " %%M in ('tasklist ^| find ^"%exe_name%^"') do (
tskill "%%M" /ID:%%U
)
)
)
endlocal
goto :eof
For all other users:
setlocal enabledelayedexpansion
set exe_name=Explorer
for /f "skip=1 tokens=1,2,3" %%S in ('query user') do (
set "current_user=%%S"
if "!current_user:~0,1!" NEQ ">" (
for /f "tokens=2 delims= " %%M in ('tasklist ^| find ^"%exe_name%^"') do (
tskill "%%M" /ID:%%U
)
)
)
endlocal
goto :eof
You can kill all processes of a particular user like this (provided you have admin privileges):
#echo off
taskkill /fi "username eq %1" /t /f
Run the script like this:
C:\>script.cmd joe
However, why don't you simply log the second user off instead of switching back? That would be the obvious (and much cleaner) solution. As admin you can even log off other users on the commandline:
logoff session
You can enumerate the sessions with query session (or qwinsta if the former doesn't work):
#echo off
for /f "tokens=3" %%s in ('qwinsta ^| find /i "joe"') do (
logoff %%s
)

Resources