Hi I'm trying to write a batch file that when it gets to that area of the code waits for 10 seconds and then if a certain key is pressed exits, otherwise it goes to another area of the code.
Here is what I got so far
SLEEP 10
IF
exit
else if
goto start
sorry, I don't know if this is correct. I'm just learning Lua and while similar to DOS they aren't quite the same. If anyone can fill in the gaps and fix the mistakes I would much appreciate it. The key I want to be pressed is either any or a specific key ID which
You can do this in batch using this
#echo off
choice /c abcd /n /t 5 /d d
if %errorlevel%==1 echo You chose a
if %errorlevel%==2 goto :CONTINUE
if %errorlevel%==3 echo You chose c
if %errorlevel%==4 exit >nul
:CONTINUE
REM Continue code
pause >nul
Usage:
In this script your options are a, b, c, and d.
Use the %errorlevel% with incrementing numbers to get the choice selected.
The /t switch is the timeout in seconds, in this it is 5 seconds.
The /d switch is the default option, use this to automatically make a choice if the command times out. In this case d will be the time out choice, which will exit the script.
Just tweak to fit your needs.
Related
With my little knowledge of writing code, I am trying to make a batch file where I can disable or enable a line in audio device with an IF statement.
For example, if the device is currently enabled, when I run the .bat file it will disable. If it's disabled, then it enables it.
I have the the device ID ("SWD\MMDEVAPI{0.0.1.00000000}.{55e90a30-8001-4bc8-af56-52998c03ed88}"). I am currently using pnputil /disable-device which works. But I don't know how to go about the IF statement. Would appreciate some help with that.
Edit: Okay so I found a tool called SoundVolumeView.exe that can lower the sound so the white noise can't be heard on startup. It can also mute as well all through command line.
I wasn't sure if you had solved this yourself already and I know I'm not supposed to spoon feed code on here but I had a script that did something similar and thought I should contribute. If you have any issues with this script, please comment with your issue.
Explaination: it runs pnputil /enum-devices /ids and looks at the output until it gets to a line with the device id. It sets a variable called ahead to 4. If ahead is above 0, then it will check if it is 0, if it isn't then it will go to the next line in the output of the command. If it is 0, then it will go to the toggle label and then it will check the line if it doesn't say Started. If it doesn't have Started in the line, then it will enable your device, if it does say started, then it will disable it. Then it just pauses and exits.
#echo off
setlocal enableDelayedExpansion
REM Needs to be run as administrator to work
set device=SWD\MMDEVAPI{0.0.1.00000000}.{55e90a30-8001-4bc8-af56-52998c03ed88}
set ahead=-1
for /f "delims=" %%a in ('pnputil /enum-devices /ids') do (
set "line=%%a"
if !ahead! GEQ 0 (
if !ahead!==0 goto :toggle
set /a ahead-=1
) else (
if not "x!line:%device%=!"=="x!line!" (
set ahead=4
)
)
)
:toggle
if "x!line:Started=!"=="x!line!" (
REM Device is not running
pnputil /enable-device "%device%" >nul
echo Enabling device...
) else (
REM Device is running
pnputil /disable-device "%device%" >nul
echo Disabling device...
)
pause
exit /b 0
For documentation on PnPUtil: https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/pnputil-command-syntax
For information on on for loops: https://ss64.com/nt/for.html, https://stackoverflow.com/a/50704943/19341457
For information on finding if a substring is in a string: https://stackoverflow.com/a/7006016/19341457
For information on delayed expansion: https://ss64.com/nt/delayedexpansion.html
I am creating a should-be-simple batch file that will allow me to input a class name and it will take me to the correct google classroom. However, my if statement doesn't work, even when I input the word "Social Studies". It does not take me to my classroom, and on top of that, the CMD is just closed. When I remove the If Statement line, the code works fine and the cmd just stays open after inputting a class.
set /p class="Enter Class: "
IF "%class%" /I EQU "Social Studies" (START https://classroom.google.com)
cmd /k
IF /I "%class%" EQU "Social Studies"...
The parsing logic for an if statement is very specific; if [/i][NOT] arg1 op arg2 where /i and not are optional, but must if used, be used in that order.
Your code sees /i where it expects a comparison-operator and generates a syntax-error.
When you use the point-click-and-giggle method of executing a batch, the batch window will often close if a syntax-error is found. You should instead open a 'command prompt' and run your batch from there so that the window remains open and any error message will be displayed.
You can write #echo off whice prevents the prompt and contents of the batch file from being displayed.
I replaced the your EQ with == and now it works:
#echo off
set /p class="Enter Class: "
IF "%class%"=="Social Studies" (START https://classroom.google.com)
PAUSE
The PAUSE at the end will make the CMD remain open after it's done
I have two questions regarding a batch script I'm working on. I realize that batch script questions are common but haven't found an answer to my exact question so I thought I'd try asking. The problematic areas are the user input sections on the menus.
There are two problems: 1) Input entered that is not one of the specified choices will cause the script to jump to random areas. And 2) some sections that use external programs are not taking the user %input% even when I know the syntax and flag use would normally be correct (as in, I can run them manually... so for some reason the input isn't capturing on them).
First issue example:
:MenuOne
echo Select one of the following options:
echo 1) x
echo 2) y
echo Q) Quit
set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit
:xoption
#REM Here goes a lot more submenus and/or options that actually run tools via cmd.
:yoption
#REM Again, menus and/or tools being invoked, in a listed menu, designed like above.
:Quit
echo Quitting...
exit
If a user types "b" at the selection prompt, I would love for the script to give an error and repeat the menu. Instead it jerks around other menus. I'm guessing that I need some ELSE statements? Does anyone have an example that I can use to accomplish this?
Second issue of some commands not using the %input% properly and returning an error as though it never received the %input%.
set /P INPUT=[Testone Input]: %testone%
set /P INPUT=[Testtwo Input]: %testtwo%
commandtorun.exe -f %testone% -h %testtwo%
Thanks!
Better to use choice (http://ss64.com/nt/choice.html) because it will persist until you set the correct input
CHOICE /C XYQ /M "Select of the following options [X,Y,Q]"
if errorlevel 1 goto :x
if errorlevel 2 goto :y
uf errorlevel 3 goto :q
Yet it's still possible to be done with IFs
set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit
rem -- will be executed only if the all the above are not true
goto :eof
For the second problem..You are not using SET /P correctly (the name of the variable should be in the front) , or you are trying something that I don't understand (where input variable is used):
set /P testone=[Testone Input]:
set /P testtwo=[Testtwo Input]:
commandtorun.exe -f %testone% -h %testtwo%
In your program as written, all your choices will fall through to the next one. If no relevant choice is entered, it will run :xoption and :yoption. Each of those should probably return to the menu after executing:
:MenuOne
echo Select one of the following options:
echo 1) x
echo 2) y
echo Q) Quit
set INPUT=
set /P INPUT=[1,2,Q]: %=%
If "%INPUT%"=="1" goto xoption
If "%INPUT%"=="2" goto yoption
If /I "%INPUT%"=="Q" goto Quit
echo Invalid selection.
echo.
goto MenuOne
:xoption
#REM Here goes a lot more submenus and/or options that actually run tools via cmd.
goto MenuOne
:yoption
#REM Again, menus and/or tools being invoked, in a listed menu, designed like above.
goto MenuOne
A real simple way to ensure a valid selection is made is to use the choice command instead of set /P. That will force the user to enter a value:
choice -c 12Q
echo %errorlevel%
The choice command will return the index of the selected character (1, 2 or 3 in the above example). A bonus is that it is case-insensitive, so you don't have to worry about checking both Q and q.
Well, I have been told time and time again that system command is bad, but I need to change a registry value and my forte is batch so I have a commmand in mind that does it:
system("REG ADD "HKCU\Control Panel\Desktop" /V Wallpaper /T REG_SZ /F /D "C:\background.bmp"");
system("REG ADD "HKCU\Control Panel\Desktop" /V WallpaperStyle /T REG_SZ /F /D 0");
system("REG ADD "HKCU\Control Panel\Desktop" /V TileWallpaper /T REG_SZ /F /D 2");
system("%SystemRoot%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");
However, using this makes Visual C++ 2010 Express highlight HKCU and the slash betweeen Panel and Desktop as an error and does not allow me to compile or debug my program. I don't want to use the system command so I was wondering how to use a C++ to preform the same registry command?
I DON'T UNDERSTAND WIN32 REGISTRY API???
And is it ok to use the system command for this
system("%SystemRoot%\System32\RUNDLL32.EXE user32.dll, UpdatePerUserSystemParameters");
because I don't know if C++ can preform the same task without it, and if it can how???
Sorry, I know it's a big question but if possible could you please include code, I am just beginning and none of the other forums make any sense and I have been looking for atlease three hours (I am not stupid with computers either)!!!
Thanks in advance
Please use the Win32 Registry API!!!
Some extra work is needed to write string literals that contain special characters. For example, in your code, the " after ADD is the end of the string.
You need to put a backspace before each special character (includes quotes and backspaces) to make sure they are put into the string instead of being processed by the compiler. This is called escaping.
The result will look like this:
system("REG ADD \"HKCU\\Control Panel\\Desktop\" /V Wallpaper /T REG_SZ /F /D \"C:\\background.bmp\"");
Using the Registry API is a better option for your task, of course, but you also needed to know how to write string literals properly.
In a DOS batch file we can only have 1 line if statement body? I think I found somewhere that I could use () for an if block just like the {} used in C-like programming languages, but it is not executing the statements when I try this. No error message either. This my code:
if %GPMANAGER_FOUND%==true(echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
Strangely neither "GP Manager is up" nor "GP Manager is down" gets printed when I run the batch file.
You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:
if <statement> (
do something
) else (
do something else
)
However, I do not believe that there is any built-in syntax for else-if statements. You will unfortunately need to create nested blocks of if statements to handle that.
Secondly, that %GPMANAGER_FOUND% == true test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.
The following sample code works fine for me:
#echo off
if ERRORLEVEL == 0 (
echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
Please note a few specific details about my sample code:
The space added between the end of the conditional statement, and the opening parenthesis.
I am setting #echo off to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo.
I'm using the built-in ERRORLEVEL variable just as a test. Read more here
Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:
if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)
This should provide var3 with the following value:
blue_cheese
but instead yields:
_
because all 3 commands are cached and executed simultaneously upon exiting the code block.
I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.
if %ERRORLEVEL%==0 goto :error0
goto :endif
:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
:endif
Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.
I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:
for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)
I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.
if "%COPYTOOL%" equ "R" (
WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
%TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
call %TOOLPATH% "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)
Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.
Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.
Maybe a bit late, but hope it hellps:
#echo off
if %ERRORLEVEL% == 0 (
msg * 1st line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue1
)
:Continue1
If exist "C:\Python31" (
msg * 2nd line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue2
)
:Continue2
If exist "C:\Python31\Lib\site-packages\PyQt4" (
msg * 3th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue3
)
:Continue3
msg * 4th line WORKS FINE rem You can relpace msg * with any othe operation...
goto Continue4
)
:Continue4
msg * "Tutto a posto" rem You can relpace msg * with any othe operation...
pause