write .bat to end opened excel.exe tasks except the older one
- User
write .bat to end opened excel.exe tasks except the older one
- Assistant
Here is a .bat script that will end all opened instances of excel.exe tasks except the oldest one:
@echo off REM Get the oldest instance ID of excel.exe for /f "skip=1 tokens=2 delims=," %%I in ('tasklist /fo csv /nh /v ^| findstr /i "excel.exe"') do ( for /f "tokens=2 delims= " %%A in ("%%~I") do ( if not defined OLDEST ( set "OLDEST=%%~A" ) else ( if %%~A lss !OLDEST! set "OLDEST=%%~A" ) ) ) REM End all instances of excel.exe tasks except the oldest one for /f "skip=1 tokens=2 delims=," %%I in ('tasklist /fo csv /nh /v ^| findstr /i "excel.exe"') do ( for /f "tokens=2 delims= " %%A in ("%%~I") do ( if %%~A neq !OLDEST! ( taskkill /f /pid %%~A >nul 2>nul ) ) ) echo All excel.exe tasks except the oldest one have been ended.Note:
- This script will only work on Windows systems as it uses the
tasklistandtaskkillcommands. - It identifies the oldest instance of excel.exe based on the process ID (PID) obtained from the
tasklistcommand. The assumption is that the PID is assigned sequentially, so the oldest instance will have the smallest PID.
- This script will only work on Windows systems as it uses the
- User
write .bat to end opened excel.exe tasks except the older one with storing excel session in csv file
- Assistant
Certainly! Here's an updated version of the .bat script that not only ends all opened instances of excel.exe tasks except the oldest one but also stores the excel session information in a CSV file before terminating them:
@echo off setlocal enabledelayedexpansion REM Set the path to the output CSV file set "outputFile=C:\Path\to\excel_sessions.csv" REM Get the oldest instance ID and session information of excel.exe (for /f "skip=1 tokens=2,5,6 delims=," %%I in ('tasklist /fo csv /nh /v ^| findstr /i "excel.exe"') do ( for /f "tokens=2 delims= " %%A in ("%%~I") do ( set "PID=%%~A" set "Session=%%~J" if not defined OLDEST ( set "OLDEST=%%~A" set "OLDEST_SESSION=%%~J" ) else ( if %%~A lss !OLDEST! ( set "OLDEST=%%~A" set "OLDEST_SESSION=%%~J" ) ) ) echo !PID!,!Session! )) > "%outputFile%" REM End all instances of excel.exe tasks except the oldest one for /f "tokens=1,2 delims=," %%A in (%outputFile%) do ( if %%A neq %OLDEST% ( taskkill /f /pid %%A >nul 2>nul ) ) echo All excel.exe tasks except the oldest one have been ended. echo Excel session information has been stored in "%outputFile%".This script will store the excel session information (process ID and session name) of all excel.exe tasks in the specified output CSV file. It will then terminate all excel.exe tasks except the oldest one. The output CSV file will have a format like this:
PID,Session 1234,Console 5678,Services ...Please replace
C:\Path\to\excel_sessions.csvwith the desired path and filename for the output CSV file.