taskkill for particular user - batch-file

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
)

Related

Output in a file a variable in batch

I would like to input a variable to a text file in batch. I've tried a couple of things but I can't seem to find the proper variable. Can anybody help?
Here's my code:
echo.
echo List of all recorded wifi networks and their passwords:
echo.
setlocal enabledelayedexpansion
for /f "tokens=2delims=:" %%a in ('netsh wlan show profile ^|findstr ":"') do (
set "ssid=%%~a"
call :getpwd "%%ssid:~1%%"
)
echo.
echo.
choice /M "Do you want to save results to a txt file?"
set path=%errorlevel%
if %path% EQU 1 goto save_to_txt
if %path% EQU 2 goto END
:save_to_txt
if not exist List.txt (
echo Output of Wifi password grabber.bat > List.txt
)
echo ssid: %ssid% pass: %%i>> List.txt
pause
exit /b
:END
echo This is the no area
pause
exit /b
:getpwd
set "ssid=%*"
for /f "tokens=2delims=:" %%i in ('netsh wlan show profile name^="%ssid:"=%" key^=clear ^| findstr /C:"Key Content"') do echo ssid: %ssid% pass: %%i
Epicurieux.
You cannot use %%i outside of the for loop. it is a temporary variable used by for. You don't need to use multiple labels either, just ask beforehand if you want to save to file:
#echo off & set outfile=
setlocal enabledelayedexpansion
if not exist list.txt echo Output of Wifi password grabber.bat>list.txt
choice /c yn /M "would you like log SSID results to file?
if not errorlevel 2 set "outfile=>>list.txt"
for /f "tokens=2*delims=:" %%a in ('netsh wlan show profile ^|find /i "All User Profile"') do (
set "ssid=%%~a"
for /f "tokens=2*delims=:" %%i in ('netsh wlan show profile name^="!ssid:~1!" key^=clear ^| findstr /C:"Key Content"') do (echo ssid: "!ssid:~1!" pass: %%i)%outfile%
)
or without setting variables in the for loops and without the need for delayedexpansion
#echo off & set outfile=
if not exist list.txt echo Output of Wifi password grabber.bat>list.txt
choice /c yn /M "would you like log SSID results to file?
if not errorlevel 2 set "outfile=>>list.txt"
for /f "tokens=2*delims=:" %%a in ('netsh wlan show profile ^|find /i "All User Profile"') do for /f "tokens=2*delims=:" %%i in ('netsh wlan show profile name^=%%a key^=clear ^| findstr /C:"Key Content"') do (echo ssid: %%a pass: %%i)%outfile%
As a result of my comment, (beneath the other currently existing answer), I searched my script personal collection for an example of something similar.
The following, (which may fail if certain things do not match the specific criteria under which this was designed), is intended to return the Profile name, the Interface name, the SSID, and the password Key.
Other than the addition of the 'results to file' portion of the code, it is tested on Windows 8+ [English]
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "LDN=_tmp"
For /F Tokens^=*^ Delims^=^ EOL^= %%G In ('Dir "%TEMP%" /B /A:D /O:N 2^>NUL'
) Do Set "LDN=%%G%LDN%"
MD "%TEMP%\%LDN%" 2>NUL || GoTo :EOF
For /F "Delims==" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe OS Call /? ^|
%SystemRoot%\System32\find.exe "=="') Do Set "HT=%%G"
(Set LF=^
% 0x0A %
)
For /F %%G In ('Copy /Z "%~f0" NUL') Do Set "CR=%%G"
%SystemRoot%\System32\choice.exe /M "Print WLAN Profile results to file"
If ErrorLevel 2 (Set "FOD=CON") Else Set "FOD=%~dp0list.txt"
For /F Tokens^=2^,4^ Delims^=^" %%G In ('%SystemRoot%\System32\netsh.exe WLAN
export profile key^=clear folder^="%TEMP%\%LDN%"') Do (Set "_=%%~nH"
Set "{="
For /F "Tokens=* Delims=" %%I In ('%SystemRoot%\System32\cmd.exe /V /S /D
/C %SystemRoot%\System32\findstr.exe /R /I /C:"<keyMaterial>"^
/C:".*!CR!*!LF![\ \%HT:~-1%]*<\/SSID>" "%%H"') Do (Set "]=%%I"
SetLocal EnableDelayedExpansion
If "!]:~-6,1!" == "/" (For %%J In ("!]:~,-7!") Do (EndLocal
Set "}=%%~J")) Else For %%J In ("!]:~,-14!") Do (EndLocal
Set "{=%%~J")
If Defined { (SetLocal EnableDelayedExpansion
For /F Tokens^=*^ Delims^=^ EOL^= %%K In ('
Echo(^| Set /P "=!_:-%%G="^&:"!" 0^<NUL') Do (
(Echo Name="%%G" Interface="%%K" SSID="!}:*>=!" Key="!{:*>=!"
) 1>>"%FOD%" & EndLocal))))
RD /Q /S "%TEMP%\%LDN%"
If /I "%FOD%" == "CON" (Setlocal EnableDelayedExpansion
For /F "Tokens=1,2" %%G In ("!CMDCMDLINE!") Do (Endlocal
If /I "%%~nG" == "cmd" If /I "%%~H" == "/C" Pause))
EndLocal
GoTo :EOF
The file list.txt, if you choose to write to one, will be located along side the batch file, %~dp0, it should create it if it does not exist, or add to it, if it does.

Is there a way to echo a list of all Drives/Partitions e.g C:\ D:\ E:\ etc and prompt the user to choose one of them to do some function?

I am wondering if there's a way to check and echo the list of all available drives/partitions on the PC and prompt the user to choose one of them by typing its letter and hitting enter to submit. Then the batch file will proceed.
The desirable outcome may be like?
#echo off
echo List all drives partitions... Hit enter to continue
C, D, E, F
echo Choose a drive to proceed
Here the user will type the preferred Drive letter
D
echo proceeding on D:\
Thanks to the responders
#echo off
setlocal enabledelayedexpansion
set "list= "
for /f "skip=1 delims=:" %%a in ('wmic logicaldisk get caption') do (
set "list=!list!%%a"
)
choice /c %list% /m "Enter drive "
set "disk=!list:~%errorlevel%,1!:"
echo you chose %disk%
If you want to limit to hard disks only, use
... in ('wmic logicaldisk where "drivetype=3" get caption') do ...
MountVol may be sufficient for your needs:
#Echo Off
SetLocal EnableDelayedExpansion
Set "i=0"&For /F "Delims==" %%# In ('Set # 2^>NUL')Do #Set "%%#="
For /F %%# In ('MountVol^|Find ":\"')Do (Set /A i+=1
Set "#!i!=%%~d#"&Echo !i!. %%~d#)
:Ask
Echo(&Set /P "Drive=Choose a drive to proceed>"
Set #|Findstr "^#%Drive%=">Nul||GoTo :Ask
Set "Drive=!#%Drive%!"
Echo(Proceeding on %Drive%&Timeout 3 >NUL
EndLocal
GoTo :EOF

Close All Program Except these with CMD

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

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

Resources