Windows batch script to create folder for each file in a directory, name it, than move the file into that folder

batchwindows

The code:

for %%X in ("C:\Info\AUGUST 2011\Checklists\DET1__*") do (echo %%X)

lists the name of the files that I would like to:

  1. Create a folder with the rest of the filename (after DET1__) as the title of the folder
  2. Move that file into that specific folder

I know it shouldn't be that hard, but I am really not familiar with using Windows for shell scripting, and I don't have access to a UNIX-style shell at work.

Best Answer

This is about a hundred times easier in PowerShell, but this should work. Better explanations of what's going on can be found in setlocal /?, set /? and for /?. Batch isn't a good language, so we have to do things like using ENABLEDELAYEDEXPANSION and the use !FILE! instead of %FILE% to prevent the batch file from setting the varibales once and never updating it. One key to remember is that filenames and foldernames cannot be the same. So you can't have both a file and a folder foo in C:\, for example.

I have not tested these really, so please do so on your own before doing anything.

@ECHO OFF
SETLOCAL
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%X IN ("C:\Info\AUGUST 2011\Checklists\DET1__*") DO (
    SET FILEPATH=%~fX
    SET FILENAME=%~nxX
    SET TEMPFILE=%~fX.tmp
    MOVE "!FILEPATH!" "!TEMPFILE!"
    MKDIR "!FILEPATH!"
    MOVE "!TEMPFILE!" "!FILEPATH!\!FILENAME!"
)
ENDLOCAL

PowerShell verion:

$Files = Get-ChildItem -Path 'C:\Info\AUGUST 2011\Checklists\' -Filter 'DET1__*'
$Files | ForEach-Object {
    $FileFullName = $_.FullName
    $TempFileName = "$($FileFullName).tmp"
    $DestinationFileName = "$FileFullName\$($_.Name)"
    Move-Item $FileFullName $TempFileName
    New-Item -Path $FileFullName -ItemType Directory
    Move-Item $TempFileName $DestinationFileName
}
Related Question