IF ERRORLEVEL with net user command - batch-file

I need help with some batch. I created this batch file using conditional processing statements to detect errors. For this batch file, NO conditional processing characters should remain. I need to remove those and use "IF ERRORLEVEL" to detect errors. We cannot use "IF %ERRORLEVEL%" or anything advanced, we are just in an introductory phase. We need to use the net user command as well. I am stuck.
Original Code that Works with Conditional Processing Statements:
#echo off
rem Check if the account already exists before creating account. If it does not exist, go to :FAIL
net user | find /i "%1" >nul 2>&1 && GOTO FAIL
rem Add a user if the account does not exist and then go to :SUCCESS
net user %1 %1 /add >nul 2>&1 || GOTO ERROR
GOTO SUCCESS
rem If the user does not already exist and is succesfully added
:SUCCESS
echo The %1 user was succesfully added.
GOTO :EOF
rem If the user already exists
:FAIL
echo The %1 user already exists on this computer.
echo Please use a different username.
GOTO :EOF
rem Send system generated errors messages to ECHO
:ERROR
echo An Error was generated when attempting to create the user
echo These are the things you can check:
echo Did you open the command prompt as administrator?
echo If passwords are required on your system, did you include one?
GOTO :EOF
:END
What I know:
If the account already exists the errorlevel is 0.
If the account does not exist and it is created, the errorlevel is 0.
If the command prompt is not run as an admin or password policy not
met, the errorlevel is 2.
Actually I don't know any of that stuff because it seems like my errorlevel is changing the more I experiment... I'm stuck... One of the command prompts I was getting errorlevel 1 so... also is GOTO :EOF conditional processing?
How do I accomplish this script? I am stuck. Tried some things but ultimately stuck. Here's what I have that I gave up on.
Code I have with no conditional processing statements and IF ERRORLEVEL:
#echo off
IF ERRORLEVEL 2 (
rem Send system generated errors messages to ECHO
echo An Error was generated when attempting to create the user
echo These are the things you can check:
echo Did you open the command prompt as administrator?
echo If passwords are required on your system, did you include one?
GOTO :EOF
)
:: Check if the account already exists before creating account. If it does not exist, go to :FAIL
net user | find /i "%1"
IF ERRORLEVEL 0 (
rem If the user already exists
echo The %1 user already exists on this computer.
echo Please use a different username.
GOTO :EOF
)
:: Add a user if the account does not exist and then go to :SUCCESS
net user %1 %1 /add
IF ERRORLEVEL 0 (
REM If the user does not already exist and is succesfully added
echo The %1 user was succesfully added.
GOTO :EOF
)
:END

The only time an error would be generated when creating a user would be right after trying to create a user, so that error check needs to move to that part of the code. However, since if ERRORLEVEL 0 means "if ERRORLEVEL is 0 or higher" and 2 is higher than 0, you need to move the IF ERRORLEVEL 2 code block between the net user add and last IF ERRORLEVEL 0 lines. Also, you want the net user to fail, so we need to redirect script flow before if errorlevel 0 gets picked up.
#echo off
:: Check if the account already exists before creating account.
net user "%~1"
IF ERRORLEVEL 2 GOTO ADD_USER
IF ERRORLEVEL 0 (
rem If the user already exists
echo The %1 user already exists on this computer.
echo Please use a different username.
GOTO :EOF
)
:: Add a user if the account does not exist and then go to :SUCCESS
:ADD_USER
net user %1 %1 /add
IF ERRORLEVEL 2 (
rem Send system generated errors messages to ECHO
echo An Error was generated when attempting to create the user
echo These are the things you can check:
echo Did you open the command prompt as administrator?
echo If passwords are required on your system, did you include one?
GOTO :EOF
)
IF ERRORLEVEL 0 (
REM If the user does not already exist and is succesfully added
echo The %1 user was succesfully added.
GOTO :EOF
)
:END
The wording of your homework only mentions conditional processing symbols, not all conditional processing in general, so that just means you can't use || or &&.

Instead of trying to create a user using net.exe's user command, and then try to handle any issues from doing so, afterwards; I would offer the following approach using the built-in WMI command line utility wmic. The idea is to check your input username against a list of all existing standard local users, (which aren't built-in/special), and only proceed if a duplicate username doesn't already exist.
#If "%~1"=="" (Echo No username provided as an input argument.
"%__AppDir__%timeout.exe" 3 /NoBreak>NUL&GoTo :EOF)
#SetLocal DisableDelayedExpansion
#Set "Usr=%~1"
#Call :UsrsLst "%Usr%"
#If ErrorLevel 2 (Echo The username already exists.
"%__AppDir__%timeout.exe" 3 /NoBreak>NUL&GoTo :EOF
)Else If ErrorLevel 1 Echo You have no existing standard local users.
#If ErrorLevel 0 Echo Creating user %Usr% . . .
#"%__AppDir__%timeout.exe" 3 /NoBreak>NUL
#EndLocal&GoTo :EOF
:UsrsLst
#For /F "Delims==" %%G In ('Set Usrs 2^>NUL')Do #Set "%%G="
#For /F Tokens^=2Delims^=^" %%G In ('^""%__AppDir__%wbem\WMIC.exe"^
Path Win32_UserProfile Where "Special!='True' And LocalPath Is Not Null"^
Assoc:List 2^>NUL^"')Do #For /F Tokens^=4Delims^=^" %%H In (
'^""%__AppDir__%wbem\WMIC.exe" UserAccount Where "SID='%%G'" Assoc:List^
/ResultRole:Name 2^>NUL^"')Do #If Not Defined Usrs (Set Usrs="%%H"
)Else Call Set "Usrs=%%Usrs%% "%%H""
#Set Usrs 2>NUL|"%__AppDir__%findstr.exe"/LI "\"%~1\"">NUL&&(Exit/B 2)||(
If Not Defined Usrs (Exit/B 1) Else Exit/B 0)
The existing line 10 is included just for demonstration purposes, you would replace that line only with the rest of your script. i.e. The code to actually create your new user account, and any subsequent verification processes.
You must not modify anything else except for the following recommendation. Between lines 4 and 5, perform some validation of the input argument, before continuing with the script. This would be a much better approach that trying to simply capture an error after trying to create your user account.
For example, here are some common Windows username requisites:
The provided username must consist of at least one character but no more than twenty characters.
The provided username must not consist exclusively of periods or whitespace.
The provided username cannot contain any of the following characters: */\[]: ;I=,+?<>"#
.

Related

How do I make a bat do something else if executed with a flag/switch (Title is probably vague)

So, I've been working on a batch script that essentially helps you with youtube-dl, essentially filing out all the data it needs to download into a directory. I want to be able to make a special shortcut that launches it, and instead of doing what it normally does, I want it to go through a text file (for example, let's call it update list.txt) and update playlists when that shortcut is run. I don't want to make another batch file that does this (for simplicity for user).
Here's what I have so far:
#echo off
:loop
title Welcome to CCF_100's youtube-dl helper!
set /A loop=loop+1
echo.Times Looped: %loop%
cd %~dp0
set /p input=Enter YouTube ID, URL, or Playlist ID:
set /p Output_Dir=Enter Directory you want to save in (Directory will be
created if it does not exist):
set /p flags=Enter flags (Optional):
if exist %Output_Dir%\ (goto Do_the_thing) else (goto make_directory)
:make_directory
mkdir "%Output_Dir%"
if /I %loop% LEQ 2 goto Do_the_thing
explorer "%Output_Dir%"
:Do_the_thing
title CCF_100's ytdl helper: currently downloading: %input% to %Output_Dir%
youtube-dl.exe -i -U %flags% -o "%Output_Dir%\%%(title)s - %%(id)s.%%(ext)s"
%input%
set /p loop=Successfully downloaded file(s). Download more?
if /i %loop%==y goto loop
if /i %loop%==Y goto loop
if /i %loop%==n goto end
if /i %loop%==N goto end
:end
exit
And yes I know the last two if statements are unnecessary.
You can get the arguments of a batchfile by reading the value of %n with n being a number between 0 and 9 or an asterisk. 0 is the batch-file itself (in the sense of the path to it) and the asterisk means any additional argument (excluding the batch-file-path).
So with that you can check for the contents of %1 and see if it is the flag you thought of or existent at all:
REM Demo only!
#echo off
if "%1"=="" (
echo no flags set
) ELSE (
echo flag set: %1
)
or change the if in a similar fashion to react to your flag only.

Batch File Using Net User "Username Not Found" Batch Hangs No Prompt

My batch script does the following:
user types in username and is added to a variable
trick to ask for password (hides input from user) and adds to variable
checks username and password authentication for domain GROUP using "net user" command
If user is found in set group, continue to map drive.
If user is not part of group restart at beginning
This script works when the username is found.
This script works when a username is found in a group
The problem is if the username is NOT FOUND.
When the user is NOT FOUND, it reports the "More help is available by typing NET HELPMSG 2221."
It just sits there and does not continue to prompt or anything.
I echoed the errorlevel and it comes out to 0, and reports the 0. However it still just sits there never reaching command prompt or going where the GOTO tells it.
I have put in errorlevels and I am unsure why it is stuck after the error message and does not continue. It is as if the batch script is not releasing from somewhere.
#echo off
:Question
Echo.
Echo.
SET /P HelperName=Enter Witness' Name:
Echo.
If %HelperName% EQU %Username% GOTO SameUserName
cls
echo hP1X500P[PZBBBfh#b##fXf-V#`$fPf]f3/f1/5++u5>%temp%\ftp.com
set /p password=What is your password? <nul
for /f "tokens=*" %%i in ('%temp%\ftp.com') do set "password=%%i"
del %temp%\ftp.com
cls
set i=0
set group=WGD
set user=%HelperName%
echo Checking if %user% is member of %group%...
for /f %%f in ('"net user %user% /domain | findstr /i %group%"') do set /a i=%i%+1
if %i% gtr 0 (goto :member)
:nomember
echo %user% is not member of %group% Please Try Again
goto :question
:member
net use L: \\10.10.10.10\foldernamehere\TEMP /user:wgd\%helpername% %password%
if [%errorlevel%]==[0] goto deletedrive
goto error
:deletedrive
net use /delete L:
goto start
It is as if the script in still in another function.
Well it seems like I was not waiting long enough for the message to finish. It hangs for a bit, then continues on through the script. The wait however for the help message to clear is a little long, if you know how to clear faster please let me know.

How to use parentheses in .bat files, set command and IF EXIST

Ok, I have batch file, just a simple one that hides and unhides folders.
I don't see why it cannot seem to execute accordingly;
Here is extended sample code:
#echo off
color a
title Folder/Drive hider Service
:jiki
echo Loading...
TIMEOUT /T 2 >nul
goto inputs
:inputs
echo Enabling security...
TIMEOUT /T 2 >nul
cls
goto menu
:menu
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)
if EXIST "%~dp0\Logan_Documents" (set status=Folder is unlocked, to open it, enter open as your `action.)`
cls
echo.
echo STATUS: %status%
echo.
echo ----------------------------------------
echo FOLDER PROTECTOR by Logan
echo ----------------------------------------
echo.
echo Lock = Lock the folder(s)
echo Unlock = Unlock the folder(s)
echo Credits = For more info
echo V = Display your current version
echo Exit = Close the program
echo.
echo ----------------------------------------
echo For more info, just ask Logan!
echo ----------------------------------------
echo.
echo Select your action, %USERNAME%.
echo.
set /p "menu=>"
if /I %menu%== lock goto lock
if /I %menu%== unlock goto unlock
if /I %menu%== credits goto credits
if /I %menu%== v goto version
if /I %menu%== exit goto exit
goto invalid
and also a lot more, and every time I go to execute the script, it just leaves the status variable blank.
Here's what I've tried.
Reconfiguring all variables through a port, which then sorts based on if exist. doesn't work, just leaves status blank.
Using different variables. (Kinda stupid but I didn't want to think that I have all these errors because of a small typo.) Still left error blank.
Appreciate all efforts to resolve my problem and get this program working!
-Logan
if exist should work fine exactly as you use it. You don't strictly need the quotes, since the names don't include spaces. Also you don't need the parentheses since it is a single command.
But then again, it should work with them as well (I actually tested this), so the only thing I can imagine is that the files or folders are not found because the script is running in the wrong directory. After all you use just the names without any path, so the current directory should contain those files.
The 'current directory' isn't necessarily the directory in which the script is saved. If you are in 'C:\Foo' and you call 'C:\Bar\Script.bat', the current directory will still be 'C:\Foo'. The same goes for starting scripts through a shortcut.
To try this, you can use echo %CD% in your script to echo the current directory.
As a possible solution, you can use %~dp0 to use the actual directory in which the batch script is saved, so you always have a starting point to start from:
REM Check if 'Encryption' exists in the same folder as the batch file.
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)
probably neither of the ifs are true, maybe because the active directory is not what you think it is. you can test this easily by inserting a set status=none above the ifs. or insert dir to see what the scrips actually sees at this point.

My batch save/load function wont work properly

So I am experimenting and trying to get better at using batch but I'm stuck on an issue, and I cant figure it out. The save/load allows the user to input a password and save it to the blah.blah, then later load it using the password. The problem is I want the program to recognize if the user has a password and if they dont, it will give them the option to exit or make a new password.
:passwordwant
cls
set /p "passwant=Enter your new password: "
(
echo %passwant%
)>save.sav
goto :passwordload
pause >nul
:passwordload
cls
echo Enter password to enter the programme
set /p "pass=>"
if %pass%== %passwant% goto :home
<save.sav(
set /p pass=
)
You can use if exist to determine if a file exists (or if not exist to determine if it doesn't).
if not exist save.sav (
echo Password not found
REM If you're using Windows XP or earlier, you need to use set /p instead of choice
choice /c:NQ /M "Press N to create a password. Press Q to quit."
if %errorlevel% equ 0 goto :passwordwant
if %errorlevel% equ 1 exit /b
)

How to check if a user is an administator? [duplicate]

This question already has answers here:
How to detect if CMD is running as Administrator/has elevated privileges?
(15 answers)
Closed 9 years ago.
As I use batch scripts a lot, I have spent a large amount of time searching the web for a pure batch implementation, that does not depend on an errorlevel reading, to check for admin rights of the current or specified user.
How can I check if a user is an administrator?
Note: This question is not a duplicate, as I don't want to have to rely on an errorlevel reading.
Having not found a batch script that did not try to either write a file to a system directory or relied on errorlevel, I wrote the following script to be usable in other scripts or as a standalone tool.
You can alter the code to work in a script, or pass a username to the program to determine whether the user is admin. If no username is specified, the program checks the admin-hood of the current user.
#echo off
setlocal EnableDelayedExpansion
if "%~1" == "" (set user=%username%) ELSE (set user=%~1)
net user %user% | find "Local Group Memberships">temp.tmp
for /f %%a in ('findstr /i "Administrators" temp.tmp') do (
echo.
echo %user% is Admin...
echo.
set isadmin=y
del temp.tmp
pause
goto:eof
)
echo.
echo %user% is not Admin...
echo.
set isadmin=n
del temp.tmp
pause
goto:eof
There is an easy way to check for admin rights. Just use the OPENFILES command and check the status. It requires Admin privileges, so you can just pipe the output to nul and check the result. I recommend that you use 2>nul as shown because 2012 Server and Windows 8 return ERRORLEVEL 0 but output "ERROR: Unable to retrieve data." This seems wrong to me (no error; but still an error message), but...
OPENFILES >nul 2>nul
IF ERRORLEVEL 1 (
ECHO.Right click on this file and select 'Run as administrator'.
PAUSE
GOTO :eof
)

Resources