I need a batch file that will toggle between running two command lines;
One being
nircmd.exe setdefaultsounddevice "Speakers"
The other being
nircmd.exe setdefaultsounddevice "Headset"
Ive tried using the existence of a .txt file as a flag, but for some reason it just always sees it as not existing. How do you make a batch file (silently) tick/tock every time it runs?
You can store the toggle value in the Batch file itself in a very simple way:
@echo off
setlocal
rem Get current value and update it
call :GetToggle
set /P "=+1" < nul >> "%~F0"
set /A "toggle%%=2"
if %toggle% equ 0 (
echo Set "Speakers"
) else (
echo Set "Headset"
)
goto :EOF
:GetToggle
rem Be sure that next line does NOT end in CR+LF:
set /A toggle=0
This method works correctly for a little less than 4096 times. If the Batch file run once everyday, this covers more than 11 years! If this is not enough for you, just add an if
command after get the toggle value to check if it exceeds 4090, and in such a case insert a breaking CR+LF characters at end of the file followed by a new line with set /A toggle=0
Note that this method also allows to know how many times the Batch file had been used, so it may be used in other scenario...