Search code examples
batch-filefor-loopcmdwildcard

How to copy folders which don't match some specified names, using Batch


I am trying to create a script to copy the folders in "C:\" which do not match a some particular names using batch file.

For e.g. Let's say we have the following folders:

  • C:\Windows
  • C:\Program Files (x86)
  • C:\Charlie
  • C:\Adam
  • C:\Program Data
  • C:\Drivers
  • C:\PerfLogs
  • etc

Because Windows',Program Files (x86)`, 'Program Data', 'Drivers'....etc. are folders created by our standard image, we don't have to copy them, but only want to copy "Adam" and "Charlie" folders. We know what the names of all these system generated folders are.

There are plenty of answers here and on forums, which show what to do for a wildcard search match (e.g. below), but in this instance I want folders NOT matching the given name, have arrows next to them, as per the image below. [![Arrows show what needs to be copied][1]][1]

I have tried using something like this, but using this options means that compiler is searching through even the sub-folders, for i.e it is checking C:\Windows*everything in this location**, which is extremely time consuming.

FOR /D %%G in ( "C:\*" ) DO ( 
IF /I %%G NEQ "C:\Windows" (
    IF /I %%G NEQ "C:\Drivers" (
        IF /I %%G NEQ "C:\inetpub" (
            IF /I %%G NEQ "C:\Intel" (
                IF /I %%G NEQ "C:\MSOCache" (
                    IF /I %%G NEQ "C:\PerfLogs" (

Solution

  • this should get you going in the right direction:

    FOR /D %%G in ( "C:\*" ) DO ( 
      IF /I %%G NEQ C:\Windows (
        echo %%G | FINDSTR /I /R ".*program.files.*" > NUL
        IF ERRORLEVEL 1 echo do something with %%G 
      )
    )