XP batch files: Create variable for current user account and find current user

Contributor Icon Contributed by seamonkey420 Date Icon December 7, 2006  
Tag Icon Tagged: Batch file programming

this is a quick batch file recipe that is more of an appetizer than a full meal. this recipe is just a quick batch file that lets you find the user who is currently logged in when the batch file is ran by using a FOR statement and the %USERPROFILE% variable in XP.


this batch file will do the following:

find the current user logged in when the file is ran
setup a variable, user, whose value will be set to the user logged in
and then echo back the user login.

    @echo off
    for /f “tokens=3 delims=\” %%i in (”%USERPROFILE%”) do (set user=%%i) 2>&1
    echo “logged in user:%user%”
    pause

this can be very useful when used in conjunction with other batch file commands.

if you want this info be put into a text file just use this command

    @echo off
    for /f “tokens=3 delims=\” %%i in (”%USERPROFILE%”) do (set user=%%i) 2>&1
    echo “%user%” > c:\%user%.txt
    pause

so lets say i’m logged in as john, a file called john.txt would be created and inside of the file the user login ‘john’ will be residing.

this command/line can be changed and used for various things such as copying files to a user’s my documents or desktop or anything where you need to use the user account.

–updated code; removed do if exist statement, used a straightforward do

Previous recipe | Next recipe |
 

Viewing 2 Comments

    • ^
    • v
    :lol: I need this file (or one like it) in a BAD way right now.....but this one did NOT work as advertised. I'm sure there's just a teeny adjustment needed in the syntax. Can someone read the syntax and help? Or tell me why it does NOT place a (username).txt file ANYWHERE in the logged-on user's profile?
    THANX!
    • ^
    • v
    Hi

    I can't see your batch file, but in this example

    @echo off
    Echo Current user: %USERNAME% > "%USERPROFILE%%USERNAME%.txt"

    <Note: the Echo line is supposed to be on 1 line if it does not show on 1 line>

    A text file will be created in the current users profile folder with their username as the file name with the text Current user: <username>

    In XP, this would be in C:Documents and Settings<username>
    In Vista, this would be C:Users<username>

    Hope this is what you were looking for.

    RLJ
 
close Reblog this comment
blog comments powered by Disqus