Jump to content

[RESOLVED] Batch - FOR, IN () DO () - Struggling with syntax


0phoi5

Recommended Posts

I'm attempting to create a FOR each user DO set a variable 'UserID' and then echo each User ID back.

 

Why does this . . .

FOR %%Z IN (SDESK1 SDESK2 SDESK3 SDESK4) DO (set UserID=%%Z echo %UserID%)

. . . not set %UserID% correctly? It just echoes as '%Z'

 

The output should technically just list each UserID one at a time;

SDESK1
SDESK2
SDESK3
SDESK4

 

Sorry, it's been a while since I used FOR in batch and I'm sure I must be getting some syntax wrong!

Cheers.

Edited by haze1434
Resolved.
Link to comment
Share on other sites

you need to stop CMD from expanding the environment variables too early (i.e. before %%Z is populated by the for loop)

try adding this before the for loop

Setlocal EnableDelayedExpansion

 

Link to comment
Share on other sites

Unfortunately, that still doesn't seem to like it.

At the moment, my script is this;

@echo off

Setlocal EnableDelayedExpansion
FOR %%Z IN (SDESK1 SDESK2 SDESK3 SDESK4) DO (set UserID=%%Z call :DoIt)

:DoIt
echo %%Z
Pause

But the output is;

%Z
Press any key to continue . . .

When it should be...

SDESK1
Press any key to continue . . .

 

Edited by haze1434
Link to comment
Share on other sites

Try using ! instead of % to delay the expression evaluation.

@echo off

setlocal EnableDelayedExpansion

FOR %%Z IN (SDESK1 SDESK2 SDESK3 SDESK4) DO (
    set UserID=%%Z
    echo !UserID!
)

 

Link to comment
Share on other sites

2 hours ago, Jason Cooper said:

Try using ! instead of % to delay the expression evaluation.


@echo off

setlocal EnableDelayedExpansion

FOR %%Z IN (SDESK1 SDESK2 SDESK3 SDESK4) DO (
    set UserID=%%Z
    echo !UserID!
)

 

 

You beauty. That got it.

Thank you!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...