Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an user exists using command prompt or batch file?

I am trying to create a script which deletes a user. I want to check if the user inputed exists so that I can say it deleted or the user does not exist.

I have already tried some previous things I have found online but none of them work. This is what I have so far.

:DelUser
cls
echo You chose to delete a user
echo ==========================
net user
echo ==========================
set UserDel=What is the name of the user you want to delete?
echo deleting user %UserDel%.....
net user | find /i %UserDel% || goto UserNoExist
net user %UserDel% /delete
echo User %UserDel% is deleted
goto Users

:UserNoExist
echo This user does not exist
pause
goto DelUser
like image 231
MangoM3lon Avatar asked Dec 03 '25 00:12

MangoM3lon


1 Answers

1) You can use the exit code of net user command. If the user exists it returns 0. %ERRORLEVEL% variable will have the exit code.

2) In order to get the input in command prompt, you should use SET command with /p.

set /p UserDel=What is the name of the user you want to delete?

So your code should look something like:

set /p UserDel=What is the name of the user you want to delete?
net user %UserDel%
if %ERRORLEVEL% EQU 0 (     
    net user %UserDel% /delete  
    echo User %UserDel% is deleted
) else (
    echo This user does not exist
)
like image 110
EylM Avatar answered Dec 05 '25 15:12

EylM