Search code examples
batch-filexcopy

Copying variable files from the same path in different folders


Good afternoon,

I'm trying to copy the files (with the same extensions but varying file names) from every user's signatures folder, into a dump folder, using batch.

For example;

I have 3 users' roaming profiles on my C: drive, the usernames are initials, followed by a tag which they all have (initials_1);

C:\Users\abc_1\AppData\Roaming\Microsoft\Signatures\test.htm
         def_1\AppData\Roaming\Microsoft\Signatures\example.htm
         ghi_1\AppData\Roaming\Microsoft\Signatures\Signature.htm

I want to be able to copy the 3 .htm files into my new folder C:\Users\Admin\Signatures

In this case the usernames are initials and there are around 100 different users so i'm trying to avoid having to do it manually.

Please let me know if this would be possible using batch or if I would have to use Vbs?

Thank you.


Solution

  • You can try this:

    @echo off
    setlocal EnableDelayedExpansion
    FOR /D %%G in ("C:\Users\*") DO (
        if exist "%%G\AppData\Roaming\Microsoft\Signatures" (
            set "name=%%~nxG"
            if not "x!name:_1=!"=="x!name!" (
                copy "%%G\AppData\Roaming\Microsoft\Signatures\*.htm" "C:\Users\Admin\Signatures\!name!_*.htm"
            )
        )
    )
    

    The line FOR /D %%G in ("C:\Users\*") DO (...) means that code inside the parenthesis gets executed for every (non-recursive, else use /D /R) directory inside the C:\Users directory. The full path of the subdirectory gets stored in %%G, for instance C:\Users\abc_1.

    if exist "%%G\AppData\Roaming\Microsoft\Signatures" (...) means the code inside those parenthesis only gets executed if the %%G directory contains a Signatures folder.

    set "name=%%~nxG" stores the name and extension (if your directory name contains a .) of the directory in %%G inside the name variable, so only abc_1, without the C:\Users\ in front of it.

    if not "x!name:_1=!"=="x!name!" (...) checks if the name contains _1 by comparing the name with _1 removed with the name itself. You need ! here instead of % because your inside parenthesis, that's why DelayedExpansion is enabled. For more information about delayed expansion, read this. Outside of a code block this would work like %variableName:StringToFind=StringToReplaceItWith%

    The copy simply copies all .htm files from the signatures directory of each user to the admin's signatures directory, but with !name! (which contains for example abc_1) prepended to it.