Windows – Batch Issue – Creating folders and Moving Documents

batchbatch filecommand linepdfwindows

I’m trying to create a batch script in Windows 7 that will look at the first 6 numbers of 100s of pdf, create a folder based on the 6 unique numbers and move the pdfs into their respected folders. (There are some .pdfs that have the same 6 unique numbers)

The below batch almost works for me. It creates the folders for each unique 6 number pds however will not move all the documents:
For Example:
The following moves to 100036 folder
100036.pdf will move, 1000361.pdf will move. 1000361copy will move.

When there is a space in the file name, it will not move to the 100036 folder.
100036 – 1.pdf, 100036 – copy.pdf will not move

Any Ideas how to fix this?

Thank you in advance:

@echo off
REM This script creates folders based on file names and moves those files into the folders.  
REM *.pdf is the search term. Change this to search for different files.   
REM md %name:~0,6% will make a directory based on the first 6 characters of the file name. Change to 5% for the first 5 characters. 
REM move %* %name:~0,6% will move the file to the directory based on the first 6 characters of the file name. Change to 5% for the first 5 characters.

for /f %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F
goto :eof

:sub1
set name=%1
md %name:~0,6%
move %* %name:~0,6%

Edited:

 @echo off
    for /f "tokens=*" %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F
    goto :eof

    :sub1
    set name=%1
    md %name:~0,6%
    move %* %name:~0,6%

Best Answer

Because for /f split using space character, in order to process full file name, you should add "tokens=*" option :

for /f "tokens=*" %%F in ('dir/b/a-d *.pdf') do call :sub1 %%F

UPDATE: It is also needed to quote mv due to space character :

move "%*" "%name:~0,6%"
Related Question