mnranees
mnranees

Reputation: 21

Why do my `for` commands run in `cmd` but not within a batch file?

I have below cmd commands, when I run these in a batch file it doesn't execute as the command prompt terminates. But when I run these one by one manually it executes.

CD /d o:\database\UK
dir *LWRKF03* *NCOM* *DTP* *LLIQ01* *LCOG01* *LCIMS02* *LCLS01* *LOLYM* *LCHUB01* *ISD* *PUKODYS01* *PUKHSSS02* /s /t:c | findstr "%date%">C:\Users\43874210\Desktop\UK\FoundFiles.TXT
for /f "tokens=5 delims= " %i in ('"dir *LWRKF03* *NCOM* *DTP* *LLIQ01* *LCOG01* *LCIMS02* *LCLS01* /s /t:c | findstr "%date%""') do copy "%i" C:\Users\43874210\Desktop\UK
for /f "tokens=5 delims= " %i in ('"dir *LWRKF03* /s /t:c | findstr "%date%""') do copy "%i" X:
for /f "tokens=5 delims= " %i in ('"dir *NCOM* /s /t:c | findstr "%date%""') do copy "%i" W:
for /f "tokens=5 delims= " %i in ('"dir *DTP* /s /t:c | findstr "%date%""') do copy "%i" T:
for /f "tokens=5 delims= " %i in ('"dir *LLIQ01* *LCOG01* *PUKODYS01* *PUKHSSS02* /s /t:c | findstr "%date%""') do copy "%i" Q:
for /f "tokens=5 delims= " %i in ('"dir *LCIMS02* *LCLS01* /s /t:c | findstr "%date%""') do copy "%i" S:
for /f "tokens=5 delims= " %i in ('"dir *LOLYM* /s /t:c | findstr "%date%""') do copy "%i" R:
for /f "tokens=5 delims= " %i in ('"dir *LCHUB01* *ISD* /s /t:c | findstr "%date%""') do copy "%i" H:

Upvotes: 0

Views: 42

Answers (1)

Stephan
Stephan

Reputation: 56238

within batchfiles, you have to use %%i instead of %i (described in for /?)

example line:

for /f "tokens=5 delims= " %%i in ('dir *LWRKF03* *NCOM* *DTP* *LLIQ01* *LCOG01* *LCIMS02* *LCLS01* /a-d /s /t:c ^| findstr "%date%"') do copy "%%i" C:\Users\43874210\Desktop\UK

(I also corrected the syntax of in (....) and added dir parameter /a-d to exclude directories)

By the way - for me it's Tokens=4

Upvotes: 3

Related Questions