Can somebody help me to adjust this script in a way that all files from the current month will be copied?
At the moment it will copy all files older than 3 days and this will not work for us.
Within a month period we create a random number of files at \\sharename\folder\source.
Here is the batch code:
set datetimef=%date:~-4%-%date:~3,2%
if not exist "\\sharename\folder\%datetimef%" mkdir "\\sharename\folder \%datetimef%"
forfiles -p "\\sharename\folder\source" -s -m *.xml /D -3 /C "cmd /c copy #file "\\sharename\folder\%datetimef%"
And it seems to work as designed.
The commented batch code below copies all files last modified this month using command xcopy (Microsoft article).
#echo off
setlocal
set "SharedFolder=\\sharename\folder"
rem Get year and month from environment variable DATE in format yyyy-mm.
rem It is required for this simple method that environment variable DATE
rem contains the date in format dd/mm/yyyy or dd.mm.yyyy with or without
rem weekday at beginning. If the format of the date string output with
rem echo %DATE% in a command prompt window is different, the line below
rem must be adapted, or the two commented lines with command wmic are
rem used because wmic returns the current date in a format independent
rem on Windows region and language settings.
set "YearMonth=%DATE:~-4%-%DATE:~-7,2%"
rem for /F "tokens=2 delims==." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS get localdatetime /VALUE') do set LocalDateTime=%%T
rem set "YearMonth=%LocalDateTime:~0,4%-%LocalDateTime:~4,2%
rem Define source and target folder.
set "TargetFolder=%SharedFolder%\%YearMonth%"
set "SourceFolder=%SharedFolder%\source"
rem Create the target folder if not already existing and verify the
rem successful creation of target folder before copying the files.
if not exist "%TargetFolder%\*" (
mkdir "%TargetFolder%"
if errorlevel 1 (
echo Error detected by %~f0:
echo.
echo Failed to create folder %TargetFolder%
echo.
echo Check availability of server and access permissions on share.
echo.
pause
endlocal
goto :EOF
)
)
rem Define date used below on command XCOPY in format mm-dd-yyyy.
set "XcopyDate=%YearMonth:~5,2%-01-%YearMonth:~0,4%
rem Copy all files last modified this month with archive attribute set.
rem The archive attribute is removed after copying on source file to prevent
rem one more copying operation of same file if this batch file is executed
rem once more this month and source file was not modified since last run.
xcopy "%SourceFolder%\*" "%TargetFolder%\" /C /D:%XcopyDate% /H /I /K /M /Q /R /Y
endlocal
You might append on command line with xcopy (SS64 article) also the options /V and /Z.
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.
echo /?
endlocal /?
goto /?
if /?
mkdir /?
pause /?
rem /?
set /?
setlocal /?
xcopy /?
I offer also a second version making this task the hard way without using xcopy with parameter /D.
#echo off
setlocal EnableDelayedExpansion
set "SharedFolder=\\sharename\folder"
rem Get year and month from environment variable DATE in format yyyy-mm.
rem It is required for this simple method that environment variable DATE
rem contains the date in format dd/mm/yyyy or dd.mm.yyyy with or without
rem weekday at beginning. If the format of the date string output with
rem echo %DATE% in a command prompt window is different, the line below
rem must be adapted, or the two commented lines with command wmic are
rem used because wmic returns the current date in a format independent
rem on Windows region and language settings.
set "YearMonth=%DATE:~-4%-%DATE:~-7,2%"
rem for /F "tokens=2 delims==." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS get localdatetime /VALUE') do set LocalDateTime=%%T
rem set "YearMonth=%LocalDateTime:~0,4%-%LocalDateTime:~4,2%
rem Define source and target folder.
set "TargetFolder=%SharedFolder%\%YearMonth%"
set "SourceFolder=%SharedFolder%\source"
rem Create the target folder if not already existing and verify the
rem successful creation of target folder before processing the files.
if not exist "%TargetFolder%\*" (
mkdir "%TargetFolder%"
if errorlevel 1 (
echo Error detected by %~f0:
echo.
echo Failed to create folder %TargetFolder%
echo.
echo Check availability of server and access permissions on share.
echo.
pause
endlocal
goto :EOF
)
)
rem Define and initialize two counters. First one counts how many files
rem are processed successfully and second one counts how many files
rem found to process. Finally those two counts should be always equal.
set "CountProcessed=0"
set "CountTotal=0"
rem Use command DIR to get just the names of all files in source folder
rem without path sorted reverse according to last modification date, i.e.
rem file modified last being returned first and oldest modified file being
rem at end of list.
rem For each file name returned by command DIR get last modification time.
rem It is necessary here to use command FOR for this task as DIR without
rem parameter /S returns just the file name and first FOR would not be
rem able to determine location of file to get last modification time if
rem the source folder is not the current folder which is not the case here.
rem Again it is important to know the format of last modification date/time
rem which depends on Windows region and language settings to correct extract
rem just year and month with a hyphen between to compare with year and month
rem of current date. The last modification time string must start with the
rem date in format dd/mm/yyyy or dd.mm.yyyy to use the code below as is.
rem On first file with a last modification year and month not matching
rem current year and month, the FOR loop processing the file names is
rem exited with a jump to label below the FOR loop as now all other files
rem in list should be outside of current month. This early loop exit could
rem result in a wrong behavior if a file has a last modification date in
rem future in comparison to current date.
rem Copying a file is done using command COPY. This command has some
rem limitations like not overwriting read-only files in target folder.
rem Success on copying the file is evaluated by the batch script. It
rem would be also possible to use XCOPY or ROBOCOPY with the appropriate
rem parameters to copy also hidden or read-only files if this is necessary.
for /F "delims=" %%I in ('dir /A-D /B /O-D /TW "%SourceFolder%\*" 2^>nul') do (
for %%F in ("%SourceFolder%\%%I") do set "LastModification=%%~tF"
if not "!LastModification:~6,4!-!LastModification:~3,2!" == "%YearMonth%" goto ProcessingDone
set /A CountTotal+=1
copy /B /Y "%SourceFolder%\%%I" "%TargetFolder%" >nul
if not errorlevel 1 (
set /A CountProcessed+=1
) else (
echo Failed to copy file %%I
)
)
:ProcessingDone
if "%CountTotal%" == "1" (
set "PluralTotal="
) else (
set "PluralTotal=s"
)
if "%CountProcessed%" == "1" (
set "PluralProcessed="
) else (
set "PluralProcessed=s"
)
echo.
echo Processed %CountProcessed% file%PluralProcessed% of total %CountTotal% file%PluralTotal% for %YearMonth%.
endlocal
This batch code could be used to move, modify or delete all files last modified this month by searching not case sensitive for copy, replace the command by something different and adapt the comments and output messages.
Related
I am trying to create a batch script to take a directory within Windows, and compress it with 7-zip using a batch script, but limit the maximum file size of each compression part to max 4GB each, limiting the total amount of revision compression sets to 7 (for a weekly backup, Monday to Sunday). The oldest will be removed on the next backup job.
I tried playing with the REM CHECK FOR REVISIONS code, but am not knowledgeable enough to understand how to proceed with this.
#ECHO OFF
REM Script created for AVIMark Backup
REM Install 7-zip and make sure to create an environment variable to allow for shortcuts
REM https://www.7-zip.org/download.html
REM set PATH=%PATH%;C:\Program Files\7-Zip\
REM echo %PATH%
REM 7z
REM 7ZIP ENVIRONMENT VARIABLE PATH
set PATH=%PATH%;C:\Program Files\7-Zip\
7z
cls
REM SET SOURCE, DESTINATION AND REVISION AMOUNT VARIABLES
SET source="C:\AVImark"
SET destination="C:\AVImarkBackup"
SET revisions=7
REM Change Directory to the source data folder
cd "%source%"
REM Run the command to compress the directory, gather the date stamp and insert compressed file into destination folder
7z a -r -v4g "%destination%\%DATE:~7,2%.%DATE:~4,2%.%DATE:~-4% Backup".7z
REM CHECK FOR REVISIONS
cd "%destination%"
for /f "skip=%revisions% eol=: delims=" %%F in ('dir /b /o-d /a-d *.7z') do #del "%%F"
EXPECTED RESULTS
I'd like to have every backup set (in its date format) to be limited to 7 revisions in total.
ie: https://imgur.com/a/Q50n0bD
ACTUAL RESULTS
There is no revision check and cleanup happening on the oldest job, it keeps adding more sets.
#echo off
setlocal
rem Script created for AVIMark Backup
rem Install 7-zip and make sure to create an environment variable to allow for shortcuts
rem https://www.7-zip.org/download.html
rem set PATH=%PATH%;C:\Program Files\7-Zip\
rem echo %PATH%
rem 7z
rem 7ZIP ENVIRONMENT VARIABLE PATH
set "PATH=%PATH%;C:\Program Files\7-Zip"
rem SET SOURCE, DESTINATION AND REVISION AMOUNT VARIABLES
set "source=C:\AVImark"
set "destination=C:\AVImarkBackup"
set "revisions=7"
set "datestamp=%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%"
rem Change Directory to the source data folder
pushd "%source%" && (
rem Run the command to compress the directory, gather the date stamp and insert compressed file into destination folder
7z a -r -v4g "%destination%\%datestamp% Backup.7z"
popd
)
rem CHECK FOR REVISIONS
pushd "%destination%" && (
rem Option 1
rem Delete by last modified filedate
forfiles /d -7 /m "*Backup.7z.*" /c "cmd /c echo del #path"
rem Or use:
rem Option 2
rem Delete by logged date. Requires datestamp yyyy-MM-dd for correct sorting
if exist Backup.log (
findstr /c:"%datestamp%" Backup.log || >> Backup.log echo %datestamp%
) else (
> Backup.log echo %datestamp%
)
for /f "skip=%revisions% delims=" %%A in ('type Backup.log ^| sort /r') do (
echo del "%%~A Backup.7z.*"
)
popd
)
Changed datestamp to yyyy-MM-dd instead of dd.MM.yyyy.
The former datestamp is better for sorting.
If you want a datestamp independant of locale, search for
wmic os get localdatetime commands on this site.
Use of pushd and popd instead of cd.
The use of && is to run following command if the last command was successful.
|| is to run following command if the last command failed.
2 options are offered for use to delete the revisions:
The 1st is the use of forfiles.
Currently as set, it will delete revisions older
than 7 days from the current date.
This might be suitable, unless no backups have been
done for 7 days which may result in no backups.
The 2nd is the use of Backup.log.
The date is appended to the log file and then the
for loop reads the log file with type, and sort
reverses the sort to make the oldest 1st and latest
last. The skip avoids the processing of the 1st
7 revisions. The rest will be used to delete the
archives by the file pattern.
Remove the code of the option not wanted.
del commands are echoed for testing. If satisfied,
remove the echoes to make the deletion actually work.
I have this BATCH file, How to make sure the source file C:\file.zip exist and it's today's file, before applying the copy submission? following is not working when I tried:
echo off
cls
echo will do a back
if [ C:\file.zip ]
then
echo found, will validate if its the file created today?
copy C:\file.zip "\\to_computer_of_enterprise\\granted\\to\\upload\\here"
else:
echo sorry do not exist
fi
Here is a batch code not using command forfiles which is by default not available on Windows XP or even former versions of Windows, only on Windows Vista and later Windows versions which is definitely the best choice for this task.
#echo off
set "FileName=C:\file.zip"
if not exist "%FileName%" goto FileNotExist
rem Get last modification date of the file.
for %%I in ("%FileName%") do set "FileDate=%%~tI"
rem Compare the first 10 characters from file date string with the last
rem 10 characters from current local date hold in environment variable DATE.
if not "%FileDate:~0,10%" == "%DATE:~-10%" goto FileNotToday
copy "%FileName%" "\\to_computer_of_enterprise\granted\to\upload\here"
goto :EndFileCheck
:FileNotToday
echo The file %FileName% is not from today.
goto :EndFileCheck
:FileNotExist
echo The file %FileName% does not exist.
:EndFileCheck
set "FileDate="
set "FileName="
The format of date string of environment variable DATE and file date referenced with %%~tI in batch code above depends on Windows Region and Language settings. So it might be necessary to slightly adapt the code and use other character indices in the IF condition comparing file date with current local date.
Run in a command prompt window the following command line to see the date format for local date and file date on your computer:
#cls & #echo Local date: %DATE% & #for %I in ("C:\file.zip") do #echo File date: %~tI
On my computer is output:
Local date: 19.08.2016
File date: 19.08.2016 10:53
Therefore the last 10 characters of environment variable DATE (local date) compared with first 10 characters of environment variable FileDate (file date) really compares the two date strings.
A solution being independent on Region and Language settings would be:
#echo off
setlocal EnableExtensions
set "FileName=C:\file.zip"
if not exist "%FileName%" goto FileNotExist
rem The command wmic requires the name of the file with full path and
rem each backslash in path must be escaped with one more backslash.
set "EscapedFileName=%FileName:\=\\%"
rem Get last modification date of the file in region independent format.
for /F "usebackq skip=1 tokens=1 delims=." %%T in (`%SystemRoot%\System32\wbem\wmic.exe DATAFILE where "name='%EscapedFileName%'" get lastmodified`) do set "FileDate=%%T" & goto GetLocalDate
rem Get current local date in region independent format.
:GetLocalDate
for /F "tokens=2 delims==." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS get localdatetime /VALUE') do set "LocalDate=%%T"
rem Compare the first 8 characters from file date string with the first
rem 8 characters from current local date string. The format is for both
rem date strings YYYYMMDD... independent on region and language settings.
if not "%FileDate:~0,8%" == "%LocalDate:~0,8%" goto FileNotToday
copy "%FileName%" "\\to_computer_of_enterprise\granted\to\upload\here"
goto :EndFileCheck
:FileNotToday
echo The file %FileName% is not from today.
goto :EndFileCheck
:FileNotExist
echo The file %FileName% does not exist.
:EndFileCheck
endlocal
For this solution the file name must be always specified with full path.
And this solution is much slower than the first one because calling twice wmic - the Windows Management Instrumentation command-line utility - takes more than a second.
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.
cls /?
copy /?
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
Note: The file existence check does not check if the existing file system entry is really a file or a folder.
This may be helpful
forfiles /d +0 /p C:\ file.zip /c "cmd /c copy #path [path_to_copy]"
the /d +0 means files with modified date of today
for more info do forfiles /?
I have been attempting to create a single batch file that will do monthly work for me with files throughout various folders.
Currently the folder C:\test\WSP\ has numerous other folders (account names) with PDF's in them. We need to:
create a folder with MM-YYYY within C:\test\WSP\{Account Name}\
and move those PDF's into that new folder. So the end result being C:\test\WSP\{Account Name}\08-2015\ with all new PDF's in there.
Then move onto the next directory C:\test\WSP\{Account Name2},
create the 08-2015 folder and move all the PDFs into C:\test\WSP\{Account Name2}\08-2015 so on and so forth.
I can do process as needed within each {Account Name} folder by placing a batch file containing:
#ECHO OFF
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set year=%%c
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set month=%%a
set MONTH="%month%"
set YEAR ="%year%""
md %YEAR%\%MONTH%
MOVE *.pdf %YEAR%\%MONTH%\
And running every month in each folder, however, there are over 200 folders here.
Is there anyway to comb through each folder, create the directory and move the PDF's into the new folder, then move onto the next directory?
Use for /d to enumerate the folders:
#echo off
for /f "tokens=2-4 delims=/.- " %%a in ('date /T') do set "year=%%c" & set "month=%%a"
set newdir=%MONTH%-%YEAR%
for /d %%d in ("C:\test\WSP\*") do (
md "%%d\%newdir%\\"
MOVE "%%d\*.pdf" "%%d\%newdir%\\"
)
pause
Here is a commented batch code for this task:
#echo off
rem Get month and year from environment variable DATE. The
rem date format depends on region and language settings for
rem the current user. The code below expects the date in
rem format DD.MM.YYYY or DD/MM/YYYY without or with weekday
rem at beginning which is the reason why referencing the
rem characters to copy from date string is done from end of
rem the string instead of beginning. Run in a command prompt
rem window echo %DATE% to see the date format of your user
rem account.
set "MonthFolder=%DATE:~-7,2%-%DATE:~-4%"
rem Use command FOR to process each non hidden and non
rem system subdirectory of specified parent directory. The
rem loop variable D holds the name of the found subdirectory
rem with complete path.
rem If the subdirectory contains 1 or more files with the
rem file extension PDF, a subdirectory with month any year
rem is created in current subdirectory in case of not already
rem existing and all PDF files are moved into this monthly
rem created subdirectory.
for /D %%D in ("C:\test\WSP\*") do (
if exist "%%D\*.pdf" (
if not exist "%%D\%MonthFolder%\*" md "%%D\%MonthFolder%"
move /Y "%%D\*.pdf" "%%D\%MonthFolder%\" >nul
)
)
set "MonthFolder="
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.
echo /?
for /?
if /?
md /?
move /?
rem /?
set /?
And see also the Microsoft article about Using command redirection operators for an explanation of >nul which redirects the information output by command MOVE about moved files to device NUL to suppress this information.
I am trying to create a windows batch file that will:
1st: List files in current directory and output to a filenamelist (Filelist_[YYY][MM][DD][hh][mm]ss])
2nd: From the given filenamelist, read each line as an input for 3rd step
3rd: Read the first line of the file and extract 7th, 9th, and and 14th string.
Delimiter can be "~", "*" and "^"
4th: Assign 7th as ISAsender variable, 9th as ISAreceiver, and 14th string as ISActrlnum.
5th: Redirect the echoed variables to a single logfile (EDI.log).
EDIT:
6th: Check ISAsender's CNtable.txt (Ex. AP_CNtable.txt for ISA's APPLESND, SS_CNtable for SAMSUNGSND) if ISActrlnum already exists or duplicate. Initially CNtable.txt contains dumped values of ISActrlnum (control numbers).
a. If there is duplicate control number found, exit with error message and output to Dupfile.txt as well as the ISActrlnum in issue. Move file to EXCEPT folder.
b. If not duplicate, insert ISActrlnum to CNtable.txt then proceed to 7th.
7th: Use IF condition for ISAsender and ISAreceiver to move the file to a correspoinding folder.
8th: Repeat 3rd-7th until 2nd step reaches EOF or finished reading each lines.
Example: From a given Filelist_20141022010101, FileName.txt contains the following having "~" as delimiter:
ISA~00~ ~00~ ~ZZ~APPLESND ~14~APPLERCV ~130214~2300~U~00401~000000001~0~T~>
GS~FA~APPLESND~APPLERCV~20130214~2300~810~X~004010
ST~997~131250001
AK1~SC~1809
AK9~A~1~1~1
SE~4~131250001
GE~1~810
IEA~1~000000001
while CNtable.txt contains:
000000004
000000002
000000003
000000005
Since ISActrlnum=000000001 does not exist in CNtable.txt, it will update CNtable.txt by appending ISActrlnum. Here only conditional statements for the ISAsender and ISAreceiver will be utilized.
So if ISAsender=APPLESND and ISAreceiver=APPLERCV move the curent file (FileName.txt) to specific directory such as C:\VP\APPLE.
Same logic for the next filename inside Filelist_20141022010101.
I was able to write code below but don't know how to get the filename from FORFILES and use it again as variable input in the FOR LOOP.
REM FileReceiver.bat
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set TIMESTAMP=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%
C:
cd "C:\VP"
FORFILES /P "C:\VP" >"FLIST.%TIMESTAMP%"
set first=1
for /f "tokens=7 delims=~" %%a in (FileName.txt) do (
if %first%==1 (
set first=0
set ISAsender=%%a
echo %ISAsender%
)
)
set first=1
for /f "tokens=9 delims=~" %%b in (FileName.txt) do (
if %first%==1 (
set first=0
set ISAreceiver=%%b
echo %ISAreceiver%
)
)
set first=1
for /f "tokens=14 delims=~" %%c in (FileName.txt) do (
if %first%==1 (
set first=0
set ISActrlnum=%%c
echo %ISActrlnum%
)
)
if %ISAsender%=="APPLESND" if %ISAreceiver=="APPLERCV" (
move FileName.txt "C:\VP\APPLE"
)
if %ISAsender%=="SAMSUNGSND" if %ISAreceiver=="SAMSUNGRCV" (
move FileName.txt "C:\VP\SAMSUNG"
)
Can anyone help me to satisfy the requirement without having to call another batch file that checks the duplicate control numbers (ISActrlnum) ?
As much as possible I want the whole code in a single bat file. Please bear with my lengthy description.
I needed to setup the entire environment you have on your computer to recode your batch file, but I think I got it.
Read the comments - the lines starting with rem - to understand the batch file and adapt it to your environment if this necessary.
#echo off
REM FileReceiver.bat
setlocal
rem Get current date and time as local time independent on Windows region settings.
for /F "tokens=2 delims==." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "dt=%%T"
rem Reformat the date and time strong to wanted format.
set "YYYY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%"
set "Min=%dt:~10,2%"
set "Sec=%dt:~12,2%"
set "TimeStamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
rem Define name of the list file containing current date and time in name.
set "ListFile=FLIST_%TimeStamp%.lst"
rem Change directory (and drive).
cd /D "C:\VP"
rem Create the list file which is good here as the list of files changes
rem while running this batch file and therefore it is better to work with
rem a list file instead of running a FOR directly for each file in the
rem directory. The list file is not included in this list as it either does
rem not exist at all or it has wrong file extension as only *.txt files are
rem listed by command DIR. The log file EDI.log has also wrong file extension.
dir *.txt /A-D /B /ON >%ListFile%
rem It might be useful to delete the log file from a previous run.
if exist EDI.log del EDI.log
rem Process each file in the list file.
for /F "delims=" %%F in ( %ListFile% ) do call :ProcessFile "%%F"
rem Delete the list file as not needed anymore. It could be also kept.
del %ListFile%
rem Exit batch file.
endlocal
goto :EOF
:ProcessFile
rem The parameter passed from first FOR is the file name in double quotes.
set "FileName=%~1"
rem Ignore the files *_CNtable.txt and Dupfile.txt in same directory.
rem Command goto :EOF just exits here from subroutine ProcessFile.
if "%FileName%"=="AP_CNtable.txt" goto :EOF
if "%FileName%"=="SS_CNtable.txt" goto :EOF
if "%FileName%"=="Dupfile.txt" goto :EOF
rem Get 7th, 9th and 14th element from first line of current file.
for /f "usebackq tokens=7,9,14 delims=~*^" %%a in ( "%FileName%" ) do (
set "ISAsender=%%a"
set "ISAreceiver=%%b"
set "ISActrlnum=%%c"
goto WriteToLogFile
)
:WriteToLogFile
rem Remove all spaces as ISAsender and ISAreceiver have
rem usually spaces appended at end according to example
rem text. Then write file name and the 3 values to log file.
set "ISAsender=%ISAsender: =%"
set "ISAreceiver=%ISAreceiver: =%"
set "ISActrlnum=%ISActrlnum: =%"
echo %FileName%,%ISAsender%,%ISAreceiver%,%ISActrlnum%>>EDI.log
if "%ISAsender%"=="APPLESND" (
rem Check for ISA control number in file AP_CNtable.txt.
%SystemRoot%\System32\Findstr.exe /X /M /C:%ISActrlnum% AP_CNtable.txt >nul
if not errorlevel 1 goto Duplicate
echo %ISActrlnum%>>AP_CNtable.txt
if "%ISAreceiver%"=="APPLERCV" (
move /Y "%FileName%" "APPLE"
echo Moved %FileName% to directory APPLE.
)
)
if "%ISAsender%"=="SAMSUNGSND" (
rem Check for ISA control number in file SS_CNtable.txt.
%SystemRoot%\System32\Findstr.exe /X /M /C:%ISActrlnum% SS_CNtable.txt >nul
if not errorlevel 1 goto Duplicate
echo %ISActrlnum%>>SS_CNtable.txt
if "%ISAreceiver%"=="SAMSUNGRCV" (
move /Y "%FileName%" "SAMSUNG"
echo Moved %FileName% to directory SAMSUNG.
)
)
rem Exit the subroutine ProcessFile.
goto :EOF
:Duplicate
rem This ISA control number is already present in file *_CNtable.txt.
echo Duplicate control %ISActrlnum% found in file %FileName%.
echo %ISActrlnum%,%FileName%>>Dupfile.txt
rem Exit the subroutine ProcessFile.
goto :EOF
I'm not sure why the list file must have the current date and time in name, but perhaps you want to keep it for some unknown reason. In this case it would be necessary to delete 2 lines in code above - the line with command del %ListFile% and the comment line above.
Updated batch code on 2014-10-07 according to changes on point 6 in question.
Have a need to find files in a folder that are older than X hours. Have to do this in batch because this is an older server that we don't want to load anything else on. This is based on Find out if file is older than 4 hours in Batch file, but that solution was written for only for one static filename. I have adjusted it for multiple files, and US date format, but the problem I am having in the file minutes it is picking up the 'a' or 'p' for am or pm. I have posted my partial solution below (does not perform date math and echos to screen filename and date/time values). Any ideas on how to get rid of a or p?
rem extract current date
for /f "tokens=1-5 delims=.,/ " %%a in ("%date%") do (
set day=%%c&set mon=%%b&set yr=%%d
)
REM Extract Current Time
for /f "tokens=1-5 delims=.:, " %%a in ("%time%") do (
set hr=%%a&set min=%%b
)
REM BUILD LIST OF FILES IN DIRECTORY
dir /B /O:N c:\mydir\*myfilestub*.* >list.txt
Rem LOOP THROUGH LIST OF FILES and CALL SUBROUTINE TO CHECK FILE DATE
For /F %%A in (list.txt) DO (CALL :CHECKFILE %%A)
GOTO :EOF
:CHECKFILE
REM CHECKING FILE %*
set filename=%*
rem extract file date and time
for /f "tokens=1-5 delims=.:,/ " %%a in ('"dir c:\mydir\%filename%|find "%filename%""') do (
set fday=%%a&set fmon=%%b&set fyr=%%c&set fhr=%%d&set fmin=%%e
)
ECHO %FILENAME% %fday% %fmon% %fyr% %fhr% %fmin%
GOTO :EOF
Thanks to http://www.dostips.com/DtTipsStringManipulation.php, I got the answer I was needing, just added a line below the for loop that was getting the file date
SET fmin=%fmin:~0,2%
It is nothing short of amazing what you can still accomplish with just DOS on a windows server. I know this script could be cleaned up and shortened I am sure, but it suits my purposes.