Batch file over network path - batch-file

I have the following batch script to make life easier at work.
Here is what it is supposed to work:
1- Drag and drop some file onto the .bat
2- Choose file's destination on the "menu"
3- Script copy's files to destination folder
4- Script executes remote procedure (that's the PSexec line)
5- Script copy's the result of the remote procedure to other folders.
And this works fine... except for a "small" detail with which i need some help.
When i try to copy the network location \10.250.39.116\d%... if i haven't previously logged into that machine it wont work.
I've been looking into the 'net use' command to overcome this, but i'm not sure if it suits my needs.
There are a total of 4 different machines i need to authenticate, dependent on the choice of the menu.
Actual Question:
Can i log in to such machines with the batch, and avoid creating duplicate connections every time i run the script ? If so, how?
Thank you for your time!
:)
I know the paths I have all point to the same place :)
#echo off
setlocal enabledelayedexpansion
ECHO.
ECHO ...............................................
ECHO PRESS 1, 2 OR 3 to select your task, or 4 to EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Compilar em Qualidade
ECHO 2 - Compilar na HSDEV
ECHO 3 - Compilar nas DEMOS
ECHO 4 - EXIT
ECHO.
SET /P M=Type 1, 2, 3, or 4 then press ENTER:
IF %M%==1 GOTO :QUAL
IF %M%==2 GOTO :HSDEV
IF %M%==3 GOTO :DEMO
IF %M%==4 GOTO EOF
:QUAL
set "PathForms6=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb6i\GH\"
set "PathForms10=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb10\GH\"
set PathCompilador=\\10.250.39.116 -u Administrator -p Password1 cmd "/C d: & cd d:\GLINTTHSIAS\GLINTTHS\compilador & GH_PRIV_10_02_Forms.bat"
set PathDestinoPriv=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PRIV\GH
set PathDestinoPub=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PUB\GH
goto :PROCESSA
goto EOF
:HSDEV
set "PathForms6=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb6i\GH\"
set "PathForms10=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb10\GH\"
set PathCompilador=\\10.250.39.116 -u Administrator -p Password1 cmd "/C d: & cd d:\GLINTTHSIAS\GLINTTHS\compilador & GH_PRIV_10_02_Forms.bat"
set PathDestinoPriv=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PRIV\GH
set PathDestinoPub=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PUB\GH
goto :PROCESSA
goto EOF
:DEMO
set "PathForms6=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb6i\GH\"
set "PathForms10=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\compilador\fmb10\GH\"
set PathCompilador=\\10.250.39.116 -u Administrator -p Password1 cmd "/C d: & cd d:\GLINTTHSIAS\GLINTTHS\compilador & GH_PRIV_10_02_Forms.bat"
set PathDestinoPriv=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PRIV\GH
set PathDestinoPub=\\10.250.39.116\d$\GLINTTHSIAS\GLINTTHS\PUB\GH
goto :PROCESSA
goto EOF
:PROCESSA
set argCount=0
for %%x in (%*) do (
set /A argCount+=1
set "argVec[!argCount!]=%%~nx"
set "pathVec[!argCount!]=%%~dpx"
)
rem echo Number of processed arguments: %argCount%
for /L %%i in (1,1,%argCount%) do (
echo Vou compilar %%i - "!argVec[%%i]!"
if exist %PathForms6%!argVec[%%i]!.* del /q %PathForms6%!argVec[%%i]!.*
if exist %PathForms10%!argVec[%%i]!.* del /q %PathForms10%!argVec[%%i]!.*
robocopy "!pathVec[%%i]!." %PathForms6% !argVec[%%i]!.fmb > nul
)
c:
cd c:\pstools
psexec %PathCompilador%
for /L %%i in (1,1,%argCount%) do (
if exist "%PathForms10%!argVec[%%i]!.fmx" (
xcopy %PathForms10%!argVec[%%i]!.fmx %PathDestinoPriv% /y
xcopy %PathForms10%!argVec[%%i]!.fmx %PathDestinoPub% /y)
)
pause

How much testing have you done with net use? Try running it twice at the command line. Notice how the output changes at the second running:
As you can see, where a connection has already been established, net use will output a summary of the connection rather than creating a duplicate connection.
If you prefer, you could use conditional execution or errorlevel checking. Using this method, you can avoid calling net use until xcopy fails, which should only be the first time. Here's a short example, simply to illustrate the mechanics:
#echo off
setlocal
ping -n 1 10.250.39.116 | find /i "TTL=" >NUL || (
echo 10.250.39.116 is offline. Unable to continue. Press any key to exit.
pause >NUL
goto :EOF
)
call :xcopy "%~1" "destination"
echo Press any key to exit.
pause >NUL
net use \\10.250.39.116\d$ /delete >NUL 2>NUL
goto :EOF
:xcopy <source> <dest_dir>
xcopy /L "%~1" "%~2" 2>NUL || (
net use \\10.250.39.116\d$ /user:username password >NUL 2>NUL
xcopy /L "%~1" "%~2"
)
goto :EOF

Related

How come running a batch script in task scheduler does not work the same way as running a batch script in file explorer?

I have a functioning script that works as intended when ran in file explorer, but I am trying to implement a way to run the script on logon. My solution was to use task scheduler, but when I run the script the status says "running," yet, the file doesn't execute.
Here is the following code:
#echo on
if exist reboot.txt goto iterate
if not exist reboot.txt goto begin
:begin
echo HOW MANY REBOOTS DO YOU WANT?
set /p input= Enter number:
type nul > reboot.txt
echo %input% >> reboot.txt
type nul > number.txt
echo 0 >> number.txt
goto iterate
:iterate
for /f " delims==" %%i in (number.txt) do set /A temp_counter= %%i+1
echo %temp_counter% > number.txt
for /f "delims=" %%i in (reboot.txt) do set Boot=%%i
echo %Boot%
if %temp_counter% GTR %Boot% (
echo Numbers match goto end
) else (
echo Numbers don't match
start shutdown.exe /r /t 60
exit
)
:end
del reboot.txt
del number.txt
exit

Update Currently Running Batch Script

Playing around with my Batch script again. It was brought to my attention that my update routine was not working correctly. Iteration 1 would result in the running script being deleted and not copying the new version from a folder I had selected. Iteration 2 now deletes the old script and copies the new script but with each line of code I change I end up with the currently running script closing, and the new updated script not launching.
Here's a snippet of the Update routine:
:Options
REM I'll set the variable here to what is set elsewhere in the script.
SET VERSION=Version 1.7
CLS
ECHO.
ECHO.
ECHO %VERSION%
ECHO.
ECHO.
ECHO ==================== OPTIONS =====================
ECHO.
ECHO 1. Update Script WIP
ECHO 2. Install entire script to Statup Folder
ECHO 3. Install individual items for auto-launch
ECHO 4. Install Windows Logout feature
ECHO 5. Uninstall
ECHO 6. Change Colors
ECHO 7. Changelog
ECHO.
ECHO =======PRESS 'Q' TO QUIT OR 'B' TO GO BACK========
ECHO.
SET OPTION=
SET /P OPTION=Select an Option:
IF /I '%OPTION%'=='1' GOTO Update
IF /I '%OPTION%'=='2' GOTO Install
IF /I '%OPTION%'=='3' GOTO I_Install
IF /I '%OPTION%'=='4' GOTO I_Logout
IF /I '%OPTION%'=='5' GOTO Uinstall
IF /I '%OPTION%'=='6' GOTO Colors
IF /I '%OPTION%'=='7' GOTO Changelog
IF /I '%OPTION%'=='q' GOTO quit
IF /I '%OPTION%'=='quit' GOTO quit
IF /I '%OPTION%'=='b' GOTO menu
IF /I '%OPTION%'=='back' GOTO menu
ECHO.
ECHO ============INVALID INPUT============
ECHO Please select a number
ECHO or select 'Q' or 'B'.
ECHO ======PRESS ANY KEY TO CONTINUE======
PAUSE > NUL
GOTO Options
:Update
ECHO.
IF EXIST "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\Shortcut Browser *.bat" (
GOTO Update_1
) ELSE (
ECHO You have not installed the script yet. Please install the script first.
)
PAUSE
GOTO Options
:Update_1
IF EXIST "%userprofile%\AppData\Local\Temp\Update.bat" (
GOTO Update_2
) ELSE (
REM Here the main script writes an update script to a batch file
ECHO DEL "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\Shortcut Browser *.bat" > "%userprofile%\AppData\Local\Temp\Update.bat"
REM I replaced the original file location with one on the desktop. The original location was on a network drive, location is confidential.
ECHO COPY "%userprofile\Desktop\Shortcut Browser *.bat" "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" >> "%userprofile%\AppData\Local\Temp\Update.bat"
ECHO CALL "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\Shortcut Browser *.bat" >> "%userprofile%\AppData\Local\Temp\Update.bat"
ECHO EXIT >> "%userprofile%\AppData\Local\Temp\Update.bat"
)
GOTO Update_2
REM Here the main script calls upon the update script
:Update_2
CALL "%userprofile%\AppData\Local\Temp\Update.bat"
REM The script seems to hang here. Either both the scripts will remain open or close or a combination depending on where CALL and START were used.
PAUSE
GOTO Options
I saw elsewhere I could have used the FC command. I didn't know about it until troubleshooting this problem. I've gotten this far and I feel I'm just missing some small trick to get the new updated script to launch.
If you need any more info let me know. I think I covered everything.
#ECHO OFF
SETLOCAL
TITLE Super Script 5000
:Options
REM I'll set the variable here to what is set elsewhere in the script.
SET VERSION=Version 1.7
CLS
ECHO.
ECHO.
ECHO %VERSION%
ECHO.
ECHO.
ECHO ==================== OPTIONS =====================
ECHO.
ECHO 1. Update Script WIP
ECHO 2. Install entire script to Statup Folder
ECHO 3. Install individual items for auto-launch
ECHO 4. Install Windows Logout feature
ECHO 5. Uninstall
ECHO 6. Change Colors
ECHO 7. Changelog
ECHO.
ECHO =======PRESS 'Q' TO QUIT OR 'B' TO GO BACK========
ECHO.
SET "OPTION="
SET /P "OPTION=Select an Option: "
IF /I "%OPTION%"=="1" GOTO Update
IF /I "%OPTION%"=="2" GOTO Install
IF /I "%OPTION%"=="3" GOTO I_Install
IF /I "%OPTION%"=="4" GOTO I_Logout
IF /I "%OPTION%"=="5" GOTO Uinstall
IF /I "%OPTION%"=="6" GOTO Colors
IF /I "%OPTION%"=="7" GOTO Changelog
IF /I "%OPTION%"=="q" GOTO quit
IF /I "%OPTION%"=="quit" GOTO quit
IF /I "%OPTION%"=="b" GOTO menu
IF /I "%OPTION%"=="back" GOTO menu
ECHO.
ECHO ============INVALID INPUT============
ECHO Please select a number
ECHO or select 'Q' or 'B'.
ECHO ======PRESS ANY KEY TO CONTINUE======
PAUSE > NUL
GOTO Options
:Update
ECHO.
IF EXIST "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\Shortcut Browser *.bat" (
GOTO Update_1
) ELSE (
ECHO You have not installed the script yet. Please install the script first.
)
PAUSE
GOTO Options
:Update_1
IF EXIST "%tmp%\update.bat" (
2>NUL DEL "%tmp%\update.bat" || GOTO Options
)
SETLOCAL
FOR %%A IN (
"%appdata%\Microsoft\Windows\Start Menu\Programs\Startup\Shortcut Browser *.bat"
) DO (
SET "old_version=%%~A"
SET "old_dir=%%~dpA"
SET "old_file=%%~nxA"
)
FOR %%A IN (
"%userprofile%\Desktop\Shortcut Browser *.bat"
) DO (
SET "new_version=%%~A"
SET "new_dir=%%~dpA"
SET "new_file=%%~nxA"
)
IF NOT DEFINED old_version (
ENDLOCAL
GOTO Options
) ELSE IF NOT DEFINED new_version (
ENDLOCAL
GOTO Options
)
(
ECHO #ECHO OFF
ECHO SETLOCAL
ECHO.
ECHO ECHO Update and restarting...
ECHO ^>NUL PING localhost -n 3
ECHO.
ECHO SET "old_version=%old_version%"
ECHO SET "new_version=%new_version%"
ECHO SET "updated_version=%old_dir%\%new_file%"
ECHO.
ECHO CALL :log /clear_log
ECHO.
ECHO IF NOT EXIST "%%new_version%%" (
ECHO CALL :log ERROR: Not exist "%%new_version%%".
ECHO EXIT /B 1
ECHO ^)
ECHO.
ECHO CALL :log Move old_version to old_version.bak.
ECHO MOVE "%%old_version%%" "%%old_version%%.bak" ^|^| (
ECHO CALL :log ERROR: Move failed to backup old version.
ECHO EXIT /B 2
ECHO ^)
ECHO.
ECHO CALL :log Copy new_version to old_version.
ECHO COPY "%%new_version%%" "%%appdata%%\Microsoft\Windows\Start Menu\Programs\Startup\" ^|^| (
ECHO CALL :log ERROR: Copy failed. Restore old version.
ECHO MOVE "%%old_version%%.bak" "%%old_version%%" ^|^| (
ECHO CALL :log ERROR: Restore old version failed.
ECHO EXIT /B 3
ECHO ^)
ECHO EXIT /B 4
ECHO ^)
ECHO.
ECHO CALL :log Delete old_version.bak.
ECHO DEL "%%old_version%%.bak" ^|^| (
ECHO CALL :log WARNING: Delete backup file failed.
ECHO ^)
ECHO.
ECHO IF NOT EXIST "%%updated_version%%" (
ECHO CALL :log ERROR: Not exist: "%%updated_version%%"
ECHO EXIT /B 5
ECHO ^)
ECHO.
ECHO ENDLOCAL
ECHO.
ECHO ECHO Ready to restart updated version
ECHO PAUSE
ECHO CALL "%old_dir%\%new_file%"
ECHO EXIT /B
ECHO.
ECHO :log
ECHO SETLOCAL
ECHO SET "log=%%tmp%%\update.log"
ECHO IF /I "%%~1"=="/clear_log" TYPE NUL ^> "%%log%%" ^& EXIT /B
ECHO IF /I "%%~1"=="/delete_log" 2^>NUL DEL "%%log%%" ^& EXIT /B
ECHO SET args=%%*
ECHO IF NOT DEFINED args EXIT /B
ECHO ECHO %%*
ECHO ^>^> "%%log%%" ECHO %%*
ECHO EXIT /B
) > "%tmp%\update.bat"
ENDLOCAL
START "Super Script 5000" "cmd /c "%tmp%\update.bat""
EXIT
:Quit
Tested on a Win7 VM. The script needs to restart on update else
weird issues may occur. CMD does not like scripts changing as it
is reading and interpreting them. Even reusing the same console
using START with /B may cause key input issues.
update.bat is overwritten every update as it stores absolute paths
so each update will be different paths with the filenames changing.
Using a wildcard with CALL may not work too well otherwise.
update.bat moves the old version to a .bak file, copies the new
version and if successful, deletes the .bak file, else moves the
.bak file to the old version. This is just to ensure a current
version always exists even if the update fails.
Changed quotes in :Options label from ' to ". Quotes are not
interchangeable like some other languages. Example: "%OPTION%"
will work if contains a space though '%OPTION%' may cause error.
I notice no SETLOCAL at the top of your full script. Advise you add
it unless you have a good reason not to.
I merged labels :Update_1 and :Update_2 into one.
Perhaps adjust Ping localhost -n number if more or less time is
needed.
Look at the %tmp%\update.log if a problem happens. Though expect
the errors to show in the console as the label :log in
update.bat echoes to console and writes to the log.

Need some input on a batch file im working on

#echo off
:options
cls
echo Please select an operation:
echo.
echo 1. Mount TrueCrypt Volume
echo 2. Start TrueCrypt
echo 3. Dismount All TrueCrypt Volumes
echo 4. Exit
set /p option=" Option: "
:files
cls
echo Please choose a file:
echo.
echo 1. Tor
echo 2. Other_files
echo 3. Main Menu
set /p file=" File: "
if %option%==1 (
goto files
)
if %option%==2 (
TrueCrypt\TrueCrypt.exe
echo Operation Complete.
pause
goto options
)
if %option%==3 (
TrueCrypt\TrueCrypt.exe /q /d
echo Operation Complete.
pause
goto options
)
if %option%==4 (
exit
)
else(
echo Invalid Input.
echo Please try again . . .
pause > nul
goto options
)
if %file%==1 (
TrueCrypt\TrueCrypt.exe /q background /e /m rm /v "Tor"
echo Operation Complete.
pause
goto files
)
if %file%==2 (
TrueCrypt\TrueCrypt.exe /q background /e /m rm /v "Other_files"
echo Operation Complete.
pause
goto files
)
if %file%==3(
goto options
)
else(
echo Invalid Input.
echo Please try again . . .
pause > nul
goto files
)
This is a batch file I typed up to call hidden and encrypted volumes made with TrueCrypt.
Now the Options "screen" works fine, each option does as it is suppose to. But the Files "screen" doesn't do anything it is suppose to, you select a file you want to open and it does nothing just sits there, it doesn't give an error or anything so that's where it stumps me.
I am relatively a noob when it comes to Batch but I do have other programming knowledge.
But I was hoping someone would be able to help!
You've got some problems with spacing, notably the if %file%==3( line. There needs to be a space between the 3 and the (. Without that space, you'll get The syntax of the command is incorrect. The batch language doesn't lend itself to code golfing, and spacing or not spacing is important.
There's a glaring logic issue, in that you're going to visit :files whether a relevant %option% has been input or not.
There are also a couple of general batch scripting conventions that may help you in the long run if you get them under your fingers now. Whenever you set a variable to a string, consider placing the set "var=value" pair in quotation marks. Also, quote each side of the comparison operator in your if statements. Such changes won't affect this script, but the habits will result in less troubleshooting in the future.
Anyway, here's your script, fixed:
#echo off
:options
cls
set option=
echo Please select an operation:
echo.
echo 1. Mount TrueCrypt Volume
echo 2. Start TrueCrypt
echo 3. Dismount All TrueCrypt Volumes
echo 4. Exit
set /p "option=Option: "
if "%option%"=="1" (
goto files
) else if "%option%"=="2" (
TrueCrypt\TrueCrypt.exe
echo Operation Complete.
pause
goto options
) else if "%option%"=="3" (
TrueCrypt\TrueCrypt.exe /q /d
echo Operation Complete.
pause
goto options
) else if "%option%"=="4" (
exit /b
) else (
echo Invalid Input.
echo Please try again . . .
pause > nul
goto options
)
:files
cls
set file=
echo Please choose a file:
echo.
echo 1. Tor
echo 2. Other_files
echo 3. Main Menu
set /p "file=File: "
if "%file%"=="1" (
TrueCrypt\TrueCrypt.exe /q background /e /m rm /v "Tor"
echo Operation Complete.
pause
goto files
) else if "%file%"=="2" (
TrueCrypt\TrueCrypt.exe /q background /e /m rm /v "Other_files"
echo Operation Complete.
pause
goto files
) else if "%file%"=="3" (
goto options
) else (
echo Invalid Input.
echo Please try again . . .
pause > nul
goto files
)
You have an infinite loop here:
:files
cls
echo Please choose a file:
echo.
echo 1. Tor
echo 2. Other_files
echo 3. Main Menu
set /p file=" File: "
if %option%==1 (
goto files
)
So if the user enters Option 1, then the IF condition will send them to the files menu which is above. The user enters, for example File 2, but %option% is still 1. The IF statement statement then sends them back to files...
To fix this you should set another label (for example, filesExecute) and have the IF statement send the control there:
if %option%==1 (
goto filesExecute
)
Now define your filesExecute label in the appropriate spot:
...
REM Add new label here.
:filesExecute
if %file%==1 (
TrueCrypt\TrueCrypt.exe /q background /e /m rm /v "Tor"
echo Operation Complete.
pause
goto files
)
if %file%==2 (
...

Skip Find Script in Batch if text not found

I have a script that should look through a text file, for its workstation ID and then assign the user next to its Workstation ID to be a local admin.
However, if the computer name is not found, I would like it to simply goto the end of the file, and exit as if it were completed successfully.
I have looked around, but I can't really think of what terms I would use to search for in google.
Any help is much appreciated.
#echo off
setlocal enabledelayedexpansion
FIND /i "%computername%" < "C:\Build\Elevate\AccessElevations.txt" >%temp%\computer.txt
FOR /F "tokens=1-6 delims=," %%a in (%temp%\computer.txt) DO (
set school=%%a
set computerid=%%b
set Model=%%c
set Serial=%%d
set user=%%e
set access=%%f
If /i "%%f" EQU "Admin" goto Elevate
If /i "%%f" EQU "NoAdmin" goto End
:Elevate
set desc=!school! - !computerid! - !model! - !serial! - !user!
echo.
echo Now creating local admin account for !user! on !computerid!
echo.
echo Description: !desc!
echo.
net localgroup Administrators "GBN\!user!" /add
net config server /srvcomment:"!desc!"
)
:End
After the FIND /i ... line
if errorlevel 1 goto :eof
which goes to the special label :eof which CMD understands as EndOfFile if the errorlevel established by find is non-zero (zero means "found it")

Loop not looping in batch file

I have an issue and can't seem to see where I am going wrong.
I have this code, that is meant to loop through a text file, and look at the last word of the line to see if the user at the start of the line should receive elevated access to their assigned laptop.
However the code just runs through once, and then exits.
#echo off
cls
echo.
echo The following script will process the entire list of students, giving each
echo student administration rights to the laptop and set the laptop description
echo where necessary.
echo.
pause
cls
FOR /F "tokens=1-6 delims=," %%a IN (accesselevations.txt) DO (
set School1=%%a
set LaptopID=%%b
set Model1=%%c
set Serial1=%%d
set User1=%%e
set Access1=%%f
If /i "%%f" EQU "Admin" goto Elevate2
If /i "%%f" EQU "NoAdmin" goto NoElevate2
:Elevate2
set Desc1=!School1! - !LaptopID! - !Model1! - !Serial1! - !User1!
echo.
echo Now creating local admin account for !user! on !LaptopID!
echo.
echo Description: !Desc1!
echo.
pause
psexec \\!LaptopID! -u GBN\!ocusr! -p !ocpw! -n 10 -e net localgroup Administrators "GBN\!User1!" /add
psexec \\!LaptopID! -u GBN\!ocusr! -p !ocpw! -n 10 -e net config server /srvcomment:"!Desc1!"
:NoElevate2
cls
Echo.
Echo User !user1! is not allowed Local Administrator rights on !LaptopID!.
pause
)
pause
:End
The file AccessElevations has confidential data in it so I am not able to post it unfortunately, however it contains something like this
School,WorkstationID,LaptopModel,LaptopSerial,StudentUsername,AdminOrNot
School,WorkstationID,LaptopModel,LaptopSerial,StudentUsername,AdminOrNot
School,WorkstationID,LaptopModel,LaptopSerial,StudentUsername,AdminOrNot
School,WorkstationID,LaptopModel,LaptopSerial,StudentUsername,AdminOrNot
...and so-on.
I hope I have given enough information, I'm fairly new here.
Thanks in advance for any light you can spread on the issue.
Toby
Use setlocal enabledelayedexpansion or you won't able to use exclamation point on variables.
Close your FOR loop before Elevate2
Change this:
If /i "%%f" EQU "Admin" goto Elevate2
If /i "%%f" EQU "NoAdmin" goto NoElevate2
To:
If /i "%%f" EQU "Admin" (CALL:Elevate2) else (CALL:NoElevate2)
Using CALL command, your script will return to the end of FOR loop after elevation operation is done, GOTO command connot do this.
Put exit/b before :NoElevate2, otherwise your script won'r return to CALL command point.
Your code should be like this:
#echo off
setlocal enabledelayedexpansion
cls
echo.
echo The following script will process the entire list of students, giving each
echo student administration rights to the laptop and set the laptop description
echo where necessary.
echo.
pause
cls
FOR /F "tokens=1-6 delims=," %%a IN (accesselevations.txt) DO (
set School1=%%a
set LaptopID=%%b
set Model1=%%c
set Serial1=%%d
set User1=%%e
set Access1=%%f
If /i "%%f" EQU "Admin" (CALL:Elevate2) else (CALL:NoElevate2))
:Elevate2
set Desc1=!School1! - !LaptopID! - !Model1! - !Serial1! - !User1!
echo.
echo Now creating local admin account for !user! on !LaptopID!
echo.
echo Description: !Desc1!
echo.
pause
psexec \\!LaptopID! -u GBN\!ocusr! -p !ocpw! -n 10 -e net localgroup Administrators "GBN\!User1!" /add
psexec \\!LaptopID! -u GBN\!ocusr! -p !ocpw! -n 10 -e net config server /srvcomment:"!Desc1!"
exit/b
:NoElevate2
cls
Echo.
Echo User !user1! is not allowed Local Administrator rights on !LaptopID!.
pause
exit/b
:End
#echo off
setlocal
cls
echo.
echo The following script will process the entire list of students, giving each
echo student administration rights to the laptop and set the laptop description
echo where necessary.
echo.
pause
cls
FOR /F "tokens=1-6 delims=," %%a IN (accesselevations.txt) DO (
set School1=%%a
set LaptopID=%%b
set Model1=%%c
set Serial1=%%d
set User1=%%e
set Access1=%%f
If /i "%%f" EQU "Admin" CALL :Elevate2
If /i "%%f" EQU "NoAdmin" CALL :NoElevate2
)
GOTO :EOF
:Elevate2
set Desc1=%School1% - %LaptopID% - %Model1% - %Serial1% - %User1%
echo.
echo Now creating local admin account for %user1% on %LaptopID%
echo.
echo Description: %Desc1%
echo.
ECHO psexec \\%LaptopID% -u GBN\%ocusr% -p %ocpw% -n 10 -e net localgroup Administrators "GBN\%User1%" /add
ECHO psexec \\%LaptopID% -u GBN\%ocusr% -p %ocpw% -n 10 -e net config server /srvcomment:"%Desc1%"
GOTO :eof
:NoElevate2
Echo.
Echo User %user1% is not allowed Local Administrator rights on %LaptopID%.
GOTO :EOF
Notes:
setlocal added to ensure environment does not get polluted by a run
Doesn't appear to be much point in setting Access1 since it isn't used.
CALL :routine rather than goto - Not a ood idea to goto within a block as some cmd versions appear to work differently. Colon is required for running internal subroutine
Within internal subroutines, can use %var% since these run in their own context.
!var! syntax is only effective when invoked by setlocal enabledelayedexpansion (not executed in original batch.)
psexec commands simply ECHOed. Need to remove the preceding echo to execute the psexec
Shouldn't a 'remove privileges' routine be applied for 'Nodamin' ?
!user! changed to %user1% in :elevate2 since user1 is established by the loop, not user.
Suitable datafile used for testing was:
School1,Workstation1ID,Laptop1Model,Laptop1Serial,Student1Username,Admin
School2,Workstation2ID,Laptop2Model,Laptop2Serial,Student2Username,NoAdmin
School3,Workstation3ID,Laptop3Model,Laptop3Serial,Student3Username,Admin
School4,Workstation4ID,Laptop4Model,Laptop4Serial,Student4Username,NoAdmin
not that hard to construct - could easily be done with a prettier version by substituting for names and other sensitive information.

Resources