MangoM3lon
MangoM3lon

Reputation: 57

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

Upvotes: 3

Views: 16335

Answers (2)

user7818749
user7818749

Reputation:

maybe just this?

@echo off & set drop=
set /p "_usern=Enter user to delete: "
for /f "tokens=1" %%i in ('net user ^| find /i "%_usern%"') do set "drop=%%i"
if defined drop (net user %drop% /delete) else (echo %_usern% does not exist)

another way is to get a list of users first, then choose a user from list, which means he/she obviously does exist:

@echo off
@for /f "skip=4tokens=1" %i in ('net user') do @echo %I
set /p "_usern=Select user from list to delete: "
net user %_usern% /delete

Upvotes: 0

EylM
EylM

Reputation: 6103

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
)

Upvotes: 1

Related Questions