I'm trying to force the user to run the script using administrative privileges:
#echo off
net session >nul 2>&1
if %errorlevel% == 0 (
echo Success: Administrative permissions confirmed.
echo.
echo Please Choose:
echo 1. Enable
echo 2. Disable
echo 3. Exit
set /p choice="> "
echo Choice: "%choice%"
) else (
echo Failure: Please run as administrator
)
pause
The net session and errorlevel lines check the privilege, and this works. The weird thing is that no matter what gets entered for choice it behaves as if it was never initialized.
The code running inside the if block works fine by itself, so I suspect the issue has something to do with how I'm checking for privileges.
Can someone explain this behavior, and any fixes?
You'd need either delayed expansion or avoid it by reorganizing your code a bit, like:
#echo off
net session >nul 2>&1
if %errorlevel% == 1 (
echo Failure: Please run as administrator
exit 1
)
echo Success: Administrative permissions confirmed.
etc.
The issue is because you are setting a variable within an If block, without delaying variable expansion.
However, you don't need the if block at all, nor do you need to set a variable for the selection.
The following method uses the || which essentially means 'if previous command produced an error', replaces the Set /P command with Choice and uses timed pauses via the Timeout command:
#Echo Off
Net Session >Nul 2>&1 || (
Echo Failure: Please run as administrator
Timeout 3 /NoBreak >Nul
Exit /B
)
Echo Success: Administrative permissions confirmed.
Echo=
Echo 1. Enable
Echo 2. Disable
Echo 3. Exit
Choice /C 123 /M "Please Choose"
If ErrorLevel 3 Exit /B
If ErrorLevel 2 GoTo Disable
Echo Enabling
Timeout 3 /NoBreak >Nul
Exit /B
:Disable
Echo Disabling
Timeout 3 /NoBreak >Nul
Exit /B
Related
I am wondering if there is a nice and clean way to add a "select all choices" when building a choice menu in batch.
Currently I have the choice setup as clear item 1, clear item 2, clear item 3 (clear all), exit, and a timeout that the user cannot see.
If I have to I will just re-add all my code to the "clear all" area. I was hoping to see if there was a way to just have the "clear all" use the defined 1 and 2 and then go back to :start like everything else.
Answer: I took Aacini's idea of the "set option" and came up with an even simpler answer. I Changed "GOTO :start"to"GOTO :ClearCache" for the "Clear All Options". Then I added a "IF %ERRORLEVEL% neq 3 GOTO :start" and after that a "GOTO :ClearCredentials". This allowed me to keep less lines than the set option and I didn't have to move my code around to have it pass to the next process.
This should allow for multiple but different clear all options for future items.
#ECHO OFF
:start
ECHO 1. Clear IE, Chrome, Temp Cache
ECHO 2. Clear Credentials in IE, Chrome, and Windows
ECHO 3. Clear All Options
ECHO 4. Exit
CHOICE /N /C:12345 /T 15 /D 5 /M "Type the number to choose an option."
IF %ERRORLEVEL%==5 GOTO TIMEOUT
IF %ERRORLEVEL%==4 GOTO Exit
IF %ERRORLEVEL%==3 GOTO ClearAllOptions
IF %ERRORLEVEL%==2 GOTO ClearCredentials
IF %ERRORLEVEL%==1 GOTO ClearCache
GOTO :start
:ClearCache
ECHO Clearing Cache...
<code here>
pause
cls
IF %ERRORLEVEL% neq 3 GOTO :start
GOTO :ClearCredentials
REM ===-----------------------
:ClearCredentials
ECHO Clearing Credentials
<code here>
pause
cls
GOTO :start
REM ===-----------------------
:ClearAllOptions
ECHO Clearing All Options...
pause
cls
GOTO :ClearCache
pause
REM ===-----------------------
:Exit
ECHO Exiting...
<code here>
pause
EXIT
REM ===-----------------------
:TIMEOUT
cls
ECHO Exiting because no choices were made in 15 seconds
:END
timeout /t 5
This is a very simple way to do that:
#ECHO OFF
:start
set option=0
ECHO 1. Clear IE, Chrome, Temp Cache
ECHO 2. Clear Credentials in IE, Chrome, and Windows
ECHO 3. Clear All Options
ECHO 4. Exit
CHOICE /N /C:12345 /T 15 /D 5 /M "Type the number to choose an option."
GOTO Option-%ERRORLEVEL%
:Option-3 ClearAllOptions
ECHO Clearing All Options
set option=3
:Option-1 ClearCache
ECHO Clearing Cache...
<code here>
pause
cls
if %option% neq 3 GOTO :start
REM ===-----------------------
:Option-2 ClearCredentials
ECHO Clearing Credentials
<code here>
pause
cls
GOTO :start
REM ===-----------------------
:Option-4 Exit
ECHO Exiting...
<code here>
pause
EXIT
REM ===-----------------------
:Option-5 TIMEOUT
cls
ECHO Exiting because no choices were made in 15 seconds
:END
timeout /t 5
I tried to write an batch file using ERRORLEVEL.
Unfortunatly it´s not working (or better not working the way I expect).
It seems to be that ERRORLEVEL is not available as an environment variable.
on cmd:
if %errorlevel% == 0 echo test
result:
no echo
on cmd:
if %errorlevel% == %errorlevel% echo test
result:
test
on cmd:
echo %errorlevel%
result:
%errorlevel%
Read about using setlocal, but setlocal cannot be executed
Any ideas?
Thank you in advance!
ERRORLEVEL requires a process or function to be carried out in order to display an input. Say for instance you wanted to Ping Google and if successful it would print out "Good" or if it failed printed out "Bad", that's where ERRORLEVEL would come into effect. You cannot use ERRORLEVEL if a process or function is not present.
EX.
echo off
goto :pingtest
cls
:pingtest
cls
ping www.google.com
if errorlevel 2 goto :good
if errorlevel 1 echo :bad
:good
cls
echo Good
echo[
pause
:bad
cls
echo Bad
echo[
pause
As you can see from the code above, there was a process involved.
Also if you get the chance could you check out my blog? http://pryrotech.weebly.com
I am learning Windows batch scripting. I need to raise errors when copy, move or delete operations fail. I have made a sample script and for some reason, when the operation fails I cannot get the ERRORLEVEL to rise. I run the script and the files either do not exist or are opened in another program and stderr messages are output to console, but ERRORLEVEL never rises, why is this? Also, is there any way to pipe stderr into a variable I could check, if I cannot get ERRORLEVEL to rise?
My code is as below:
`#Echo Off
ECHO.
Set /P myVar=Please enter a value:
Echo var = %myVar%
ECHO Trying to delete the file dummy.csv >> log.txt
Set myVar2 = nothing
DEL C:\dummy420.csv
IF NOT ERRORLEVEL 0 ECHO There was an error
ECHO %ERRORLEVEL%
REM 2>myVar2
REM Echo 2>
REM Echo %myVar2%
Echo 2>&1
REM && (echo yourCommand was successful) || (echo yourCommand failed)
IF NOT ERRORLEVEL 0 ECHO There was an error
ECHO %ERRORLEVEL%
Move ""C:\dummy420.csv" D:\"
IF NOT ERRORLEVEL 0 ECHO There was an error
Set /P dummy=Press Enter to End`
This is my output:
Please enter a value:hello
var = hello
C:\dummy420.csv
The process cannot access the file because it is being used by another process.
0
ECHO is off.
0
The filename, directory name, or volume label syntax is incorrect.
Press Enter to End
DEL command does not change the errorlevel - more info
Check the debenham suggestion to detect failed deletion:
3>&2 2>&1 1>&3 del C:\dummy420.csv|findstr . && echo DEL failed || echo DEL succeeded
to change errorlevel:
3>&2 2>&1 1>&3 del C:\dummy420.csv|findstr .&& cmd /c exit /b 1
I made a custom start script for my Minecraft server so i could use more RAM.
When you stop the server, it asks if you want to restart or if you want to stop.
I can't get it to restart it automatically if you don't answer after 20sec
(in case of a crash). Please help.
#echo off
title minecraft-server-1.8.3
color 0A
prompt [server]:
cls
:start //starts the server
echo loading server...
java -Xms3G -Xmx3G -jar minecraft_server.1.8.3.jar nogui
cls
[code to restart the server when it didn't get an anwser in 20sec]
:choice //what to do when
set /P a=do you want to restart[Y/N]? the server stops
if /I "%a%" EQU "Y" goto :restart
if /I "%a%" EQU "N" goto :stop
goto :choice
:restart
cls
echo server will restart
TIMEOUT /T 5
cls
goto :start
:stop
cls
echo closing server
TIMEOUT /T 5
exit
Instead of set /p use choice:
choice /c YN /t 20 /d Y /m "Do you want to restart "
/c YN states the answer set (Y or N, case insensitive by the way).
/t 20 states a timeout of 20 seconds.
/d Y states the default answer Y once the timeout expires.
/m "..." states a prompt.
choice sets errorlevel to the index of the input (Y:1, N:2) so to check the user input use:
if %errorlevel% equ 1 goto :restart
if %errorlevel% equ 2 goto :stop
You can find more information about choice at http://ss64.com/nt/choice.html or type choice/?
Will this work on Windows 8 and always work? I've tested it on Windows 7 but I'm not sure... I had a friend test it and he said that it coudn't find the correct path but I checked and the syntax of the commands is the same and I don't know why there'd be a problem. This is assuming %USERPROFILE%\Documents\My Games\Terraria\Players and %USERPROFILE%\Google Drive exists already
#echo off
echo Administrative permissions required. Detecting permissions...
net session >nul 2>&1
if %errorLevel% == 0 (
echo Success: Administrative permissions confirmed.
) else (
echo Failure: Current permissions inadequate. Please run as administatior.
pause >nul
exit
)
echo ---------------------------------------------
echo Below enter "S" for simple install type or "A" for avanced install type.
echo (Simple is recommended, only use advanced if you know what your doing!)
echo ---------------------------------------------
set /p option=Enter:
if /i "%option%"=="S" goto simple
if /i "%option%"=="A" goto advanced
echo Your entry did not match available options. Try again.
pause >nul
exit
:simple
mklink /d "%USERPROFILE%\Google Drive\Terraria" "%USERPROFILE%\Documents\My Games\Terraria\Players"
cd %USERPROFILE%\Google Drive\Terraria\
copy /y NUL marker >nul
cd %USERPROFILE%\Documents\My Games\Terraria\Players
if exist marker (
echo Validation of installation complete. Symbolic link functional.
del marker
) else (
echo SOMETHING WENT WRONG!!!!!!!!
)
echo ==============
echo You Selected Simple. & echo.If there are no errors above, your installation should be complete.
echo ==============
pause >nul
exit
:advanced
mkdir "%USERPROFILE%\Google Drive\Terraria"
mklink /d "%USERPROFILE%\Google Drive\Terraria\Players" "%USERPROFILE%\Documents\My Games\Terraria\Players"
cd %USERPROFILE%\Google Drive\Terraria\Players
copy /y NUL marker >nul
cd %USERPROFILE%\Documents\My Games\Terraria\Players
if exist marker (
echo Validation of installation complete. Symbolic link functional.
del marker >nul
) else (
echo SOMETHING WENT WRONG!!!!!!!!
)
echo ==============
echo You Selected Advanced. & echo.If there are no errors above, your installation should be complete.
echo ==============
pause >nul
exit
If delivered that all paths exist....
mklink command was introduced in Vista so the script won't work on XP/2003.