简体   繁体   中英

Batch file that looks for a folder that contains 1 file

i have a lot of folders with a random number of files within. And the most of them just have 1 file inside it, these files needs to move to the parent folder. but i don't know how i should do it with a batch file.

I use Windows 7 Ultimate

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /d /r "%sourcedir%" %%a IN (*) DO (
 FOR /f %%c IN ('dir /b/a-d "%%a\*.*" 2^>nul ^|find /c /v ""') DO IF %%c==1 ECHO(MOVE "%%a\*.*" "%%a\..\"
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

The for /d /r finds all of the subdirectory names starting at sourcedir and assigns thenm to %%a in turn.

Each directory is then examined for filenames only; the 2>nul suppresses error messages for empty directories, and the output of the dir command is fed to find which counts (/c) the number of lines which don't match "" (ie. counts the lines of directory = # files returned). This is applied to %%c

If %%c is 1, then move all (one) files from the directory to its parent.

The required MOVE commands are merely ECHO ed for testing purposes. After you've verified that the commands are correct , change ECHO(MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved )

This solution don't use any external .exe command, so it should run faster. Also, it is clear enough to be understood with no problems, I think...

@echo off
setlocal EnableDelayedExpansion

for /D %%d in (*) do (
   set "firstFile="
   set "moreThanOneFile="
   for %%f in ("%%d\*.*") do (
      if not defined firstFile (
         set "firstFile=%%f"
      ) else (
         set "moreThanOneFile=true"
      )
   )
   if not defined moreThanOneFile move "!firstFile!" "%%d"
)

You have a number of folders that all may or may not contain files within them, and you want to move all files to some other directory?

PowerShell is the new and improved super charged version of using a batch file, and this is how you'll do it.

  1. Run PowerShell
  2. paste in the following

    dir -Recurse C:\\FolderContainingManySubfolder | ? PSIsContainer | dir -Recurse | move-item -Destination T:\\somePath -WhatIf

Replace C:\\FolderContainingManySubfolder with the folder that has all of those other folders with one or two items each, and replace T:\\somePath with the place you want the single files to go.

Run it, and you'll see a lot of 'What If' output, which shows you what would happen if you were to run the command. If you're happy with what you see, then remove the -WhatIf parameter from the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM