Search code examples
for-loopbatch-filecmd

CMD script: using "for" loop


I have to write simple CMD script, it has to create main folder and ten subfolders inside.Then I have to copy all the files that starts with "a" letter from system32 to the first subfolder, the files that starts with "b" letter from system32 to the second subfolder and all remaining to the last folder.

I have only problems with the last part, I don't know how to exclude previously copied files.

@echo off
rd /s /q %main%
echo Name of main folder
set /P main=
echo Names of subfolders
set /P subfolder=
mkdir %main%

for /L %%D in (1,1,10) do (mkdir "c:\Users\tomek\Desktop\%main%\%subfolder%_%%D")
for  %%Z in ("C:\Windows\System32\a*.dll") do (
copy %%Z "%main%\%subfolder%_1"
)
for  %%X in ("C:\Windows\System32\b*.dll") do (
copy %%X "%main%\%subfolder%_2"
)
for  %%Y in ("C:\Windows\System32\*.dll") do (
if not "!%%~nY:~0,1!"=="a" (copy %%Y "%main%\%subfolder%_10")
)

I've tried to exclude firstly files that starts with "a". The CMD syntax is really unintuitive to me, can someone help me?


Solution

  • for has no internal method to ignore somthing, so you have to do it yourself - for example with findstr /i /v /b (see for /? for what those switches do) (undocumented: with findstr, you can concatenate the switches as /ivb)

    for /f "delims=" %%Y in ('dir /b /a-d C:\Windows\System32\*.dll ^|findstr /ivb "a b"') do (
    

    (as you define 10 subfolder, I assume you want to copy A* to I* to the first nine, so "the rest" can be written as dir ... |findstr /ivb "[a-i]" )