-1

Before I start posting code I am wondering if this is even feasible.

I have a directory of folders I need to move to a new directory. But I only need to move the folders that contain only 2 files in them. The rest of the folders have more than 2 files in them, but they need to stay. So would this be feasible with a batch file?

  • 2
    Yes it would be feasible. Once you've researched, wrote and tested your code, if it fails to work as intended, [edit your question](https://stackoverflow.com/posts/56918126/edit) to seek the specific help you need for the issue it's exhibiting. – Compo Jul 06 '19 at 22:51

1 Answers1

0

This was interesting so I took a stab at it:

@echo off

set "dir=C:\Your\Current\Directory"
set "ndir=C:\Your\New\Directory"

setlocal enabledelayedexpansion
for /d %%A in (%dir%\*) do (
    pushd "%%A"
    for /f %%B in ('dir /a-d-s-h /b ^| find /v /c ""') do (
        set cnt=%%B
        if "!cnt!" == "2" (if not exist "%ndir%\%%~nA" robocopy "%%A" "%ndir%\%%~nA" /e)
    )
)

pause

I kept running into issues so I modified a few things to make it do what I wanted; there're likely more elegant ways to go about it, but this worked ¯\_(ツ)_/¯. First thing is setting variables for your current directory (dir) and your new directory (ndir) to make it a little easier to digest later on; we also need to enable delayed expansion since the value of our counting variable (cnt) will change between loop iterations. The first FOR loop is /d, which will loop through folders - we set each of those folders as parameter %%A and use that to change our directory (using pushd) prior to running our nested commands.

The second FOR loop is /f, which will loop through command results - the commands in this case being dir and find. For dir we are specifying /a to show all files that -d aren't folders, -s system files, or -h hidden files, and we display that output in /b bare format. Using the output from dir, we run find and specify to /v display all non-empty lines and then /c count the number - which becomes parameter %%B.

Finally, we set %%B as our counting variable (cnt) - if !cnt! is equal to 2, we see if the folder already exists in the new directory, and if it does not we robocopy it over. The move command was giving me some trouble because the folder would be locked by the loop, so if you want you could also throw in a DEL command to delete the original folder.

Let me know if that helps! Hopefully your research was going well anyway.

References: Counting Files, FOR Looping, pushd, DIR, FIND, robocopy

mael'
  • 453
  • 3
  • 7