I have something that makes a new folder with files in every night. Does anyone know how to create a script that will copy the content of the newest/latest folder to a network share and overwrite any of the files and folders in the network share? Been scratching my head for awhile.
Thanks in advance.
Something like this might serve your purpose:
SET "src_root=D:\root\for\source\directories"
SET "tgt_path=\\NETWORK\SHARE\target\path"
DIR "%src_root%" /B /AD /O-D /TC > "%TEMP%\dirlist.tmp"
< "%TEMP%\dirlist.tmp" SET /P last_dir=
FOR /D %%I IN ("%tgt_path%\*") DO RD "%%I" /S /Q
DEL "%tgt_path%\*" /Q
XCOPY "%src_root%\%last_dir%\*" "%tgt_path%" /S /E
The src_root
variable is supposed to contain the path to the folder where your daily folders are created, and tgt_path
is the target path for the latest folder's contents to copy.
The DIR
command is set up to return the contents of the root folder in the following manner:
no extra information in the output, only names (/B
);
no files, just folders (/AD
);
sort (/O…
) the output in the descending (…-…
) order of folder date (…D
);
the date is that of the folder's creation (/TC
).
The output is redirected to a temporary file, whose first line is then read into a variable (the SET /P
command). That piece of information, together with the root path and the target path, is ultimately used first with deleting, then with copying files.
The deleting is done in two steps: first the folders (the RD
command in the FOR /D
loop), then the files (DEL
). I'd like to note at this point that this script doesn't assume intervention at any stage on your side, which I understood was your intention. Consequently, it doesn't expect a confirmation to delete the files and folders at the target path, so, when you run the script, the old contents will be deleted silently (which is the effect of the /Q
switch used with both RD
and DEL
).
The copying is done with XCOPY
, as it allows us to retain the structure of the source folder (the /S
switch), including empty subdirectories (/E
), if any.
You can get more information on every command mentioned here by invoking any of them with the /?
switch at the command prompt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With