Search code examples
batch-fileautomation

Batch script to acquire all users list of local machine


Batch script to find all users having account in local machine except currently logged in user and other default users.

Code :

@echo off
SET "Value="
SET Users="dir C:\Users\ /B"
FOR /F "tokens=1*" %%A IN ('%Users%') DO (
    SET "Name=%%A"
    IF /I "%NAME%" NEQ "Administrator" (
        IF /I "%NAME%" NEQ "Public"(
            IF /I "%NAME%" NEQ %USERNAME% (
                SET "Value=%Value% "
                SET "Value=%Value%%%A"

            )
        )
    )
)
echo %Value%

Is this logic correct ? Having issue with syntax. Open to suggestions. And i want to store all users in a single variable.

I think the above script when corrected will o/p like this : user1 user2...

But i want to use newline function instead of space as delimiter. Something like :

user1
user2

Solution

  • @echo off
    SET "Value="
    SET Users="dir C:\Users\ /B"
    setlocal enableDelayedExpansion
    FOR /F "tokens=1*" %%A IN ('%Users%') DO (
        SET "Name=%%A"
        IF /I "!NAME!" NEQ "Administrator" (
            IF /I "!NAME!" NEQ "Public" (
                IF /I "!NAME!" NEQ !USERNAME! (
                    SET "Value=!Value! "
                    SET "Value=!Value!%%A"
    
                )
            )
        )
    )
    echo %Value%
    

    You need delayed expansion and you've missed one space before one of the opening brackets.