Reputation: 18737
In a batch file, I need to check if given user exists, then execute different commands according to results.
Username is taken as a parameter during bat file call on cmd.
What I want is something like that:
IF userExists (
do something
) else (
do something else
)
Following code can retrieve number of matching results, but I failed to use it in IF statement.
set username=%1
set searchUser="net user |find /c %username% "
for /F "tokens=*" %%i IN (%searchUser%) do set userCount=%%i
I expect to use userCount
in if statement, but failed to do so.
How can I use my userCount
in if statement, or is there a better approach for this?
Upvotes: 0
Views: 1039
Reputation: 38654
If you are simply trying to determine if a particular user account exists, instead of how many matching user names exist on the same PC, then I'd suggest this wmic alternative:
@Echo Off
Set "ProfilePath="
For /F "Skip=1Delims=" %%A In ('WMIC UserAccount Where^
"LocalAccount='TRUE' And Name='%~1'" Get SID 2^>Nul') Do For /F %%B In ("%%A"
) Do For /F "Tokens=2Delims==" %%C In ('WMIC Path Win32_UserProfile Where^
"SID='%%B' And Special!='True'" Get LocalPath /Value 2^>Nul'
) Do For /F "Tokens=*" %%D In ("%%C") Do Set "ProfilePath=%%D"
If Defined ProfilePath (Echo User Profile %1 exists at %ProfilePath%) Else (
Echo User Profile %1 does not exist)
Pause
The If
command along with the Pause
are included just to show you an If
|Else
structure for your further commands, (they could obviously be modified/changed as required).
If you do not need to know and/or access the user profile path, you can simplify the command considerably:
@Echo Off
WMIC UserAccount Where "LocalAccount='TRUE' And Name='%~1'" Get SID 2>Nul|Find "S-">Nul && (
Echo User Profile %1 exists) || Echo User Profile %1 does not exist
Pause
Upvotes: 1
Reputation:
Firstly, %username%
is a predefined environment variable, select somethig else like myuser
As per your original attempt using the count.
@echo off
set myname=%~1
for /F %%i IN ('net user ^| find /I /C "%myname% "') do (
if not "%%i"=="0" (
echo found %%i Matches of username
) else (
echo %%i matches found.
)
)
Else, using %errorlevel%
@echo off
set "myuser=%~1"
net user |findstr /I /R /C:"\<%myuser%\>"
if not "%errorlevel%"=="0" (
echo %myuser% does NOT exist!
) else (
echo %myuser% exists!
)
Alternatively in a for
loop:
@echo off
set "myuser=%~1"
for /f %%i in ('net user ^| findstr /I /R /C:"\<%myuser%\>"') do (
if /i "%%i"=="%myuser%" echo myusers exists!
) else (
echo %myuser% does NOT exist!
)
)
Upvotes: 1