For do if exist loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Beach Boy
Posts: 9
Joined: 27 Jul 2013 10:40

For do if exist loop

#1 Post by Beach Boy » 27 Jul 2013 10:46

Could someone please assist with the correct syntax for this? It errors out after seeing the second file in the string if it doesn't exist.

Thank you,

for /f "tokens=*" %%X in (hal.dll halacpi.dll halmacpi.dll kernel32.dll ntdll.dll ntoskrnl.exe win32k.sys winload.exe winsrv.dll) do (if exist %%X (
echo %%X
if not exist %%X (
echo %%X does not exist.
) else (
Copy %%X C:\BOOTFILES\
)
)
)

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: For do if exist loop

#2 Post by aGerman » 27 Jul 2013 14:13

You should use a simple FOR loop instead of FOR /F.

Code: Select all

@echo off &setlocal

if not exist C:\BOOTFILES\ md C:\BOOTFILES
pushd "%SystemRoot%\system32"
for %%X in (
  hal.dll
  halacpi.dll
  halmacpi.dll
  kernel32.dll
  ntdll.dll
  ntoskrnl.exe
  win32k.sys
  winload.exe
  winsrv.dll
) do (
  if exist %%X (
    echo %%X
    copy %%X C:\BOOTFILES\
  ) else (
    echo %%X does not exist.
  )
)
popd

pause

Regards
aGerman

Beach Boy
Posts: 9
Joined: 27 Jul 2013 10:40

Re: For do if exist loop

#3 Post by Beach Boy » 27 Jul 2013 15:12

Thank you greatly aGerman. That works!

Post Reply