Batch file - date variables and moving files with variable date file name from one folder to another - variables

I need some assistance, please. I'm trying to create a batch file to move files from one folder to another. The file name will have variable yyyy-mm format plus additional data before or after the date. The batch will need to move the file to a server directory with the same mmmm-yy folder name.
I've come up with the code below, but it doesn't quite work.
A "Missing Operand" error is returned.
The new directory is created but the files are not moving from the old folder to the new one.
My code:
#echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A MONTH=%%D
SET /A YEAR=%%F
)
:: Set month to last month
set /a MONTH=%MONTH%-1
:: If month equals zero, reset to 12
if %MONTH%==0 set MONTH=12
:: If month < 10, fill with zero
if %MONTH% LSS 10 set MONTH=0%MONTH%
:: If month = 12, subtract one year
if %MONTH%==12 set /a YEAR=%YEAR%-1
SET FILEDATE=%YEAR%-%MONTH%
SET FOLDER2=E:\ARCHIVE\%FILEDATE%
MKDIR %FOLDER2%
:: trying to recreate the format MOVE C:\FOLDER1\\*2013-07*.* E:\FOLDER2\2013-07 which does work
MOVE C:\FOLDER1\\*%FILEDATE%*.* %FOLDER2%
:END
EXIT
EDIT: Both responders below really helped. I tried to vote them up, but I guess my reputation is not good. Mother was right - guard your repuation! It will get you far. :)

You should better use %date%, not wmic, but you can try:
for /f "skip=1 delims=" %%a in ('WMIC Path Win32_LocalTime Get Month^,Year /Format:table') do for /f "tokens=1,2" %%b in ("%%a") DO SET "month=%%b" &SET "year=%%c"

Just a minor edit - it looks like it should work - as your explanation says the folder is being created just fine.
MOVE "C:\FOLDER1\*%FILEDATE%*" "%FOLDER2%"

Related

I need a batch program to find the folder name inside another folder [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
For example
consider:
H:\reports\test\12345\dailynews.pdf
I want to send this PDF through mail by using MSSQL job (sql server 2008 R2).
But every time when another job creates the pdf file the location changes.
like
H:\reports\test\48596\dailynews.pdf
I need a batch program to find the folder name which is present after the test folder.
A recursive check may report same named files existing elsewhere in the tree and may take longer. My suggestion is to use this instead:
#Echo Off
Set "MyFile="
For /D %%A In ("H:\reports\test\*"
) Do If Exist "%%A\dailynews.pdf" Set "MyFile=%%~fA\dailynews.pdf"
If Not Defined MyFile Exit/B
Echo %%MyFile%% = %MyFile%
Regarding the given info, I would suggest to
split the string at the backslashes and extract the 4th element like this:
set p=H:\reports\test\12345\dailynews.pdf
for /F "delims=\ tokens=4" %%a in ("%p%") do echo %%a
Note the double quotes ("%p%"), so it gets interpreted as string (and not as a filename or command).
If you want to make sure, that the 3rd element is the test folder, then I would suggest:
set p=H:\reports\test\12345\dailynews.pdf
set o=H:\reports\live\55555\dailynews.pdf
for /F "delims=\ tokens=3,4" %%a in ("%p%") do if "%%a"=="test" echo %%b
for /F "delims=\ tokens=3,4" %%a in ("%o%") do if "%%a"=="test" echo %%b
Outputs 12345 but not 55555, which is in the live folder.
Edit:
I realized that my answer left out completely, how one can detect the newest dailynews.pdf, which is what the OP probably looking for.
Like the dailynews routine runs at 21.00, and you want to mail that report at 22.00. (Again, yet another assumption.)
IMO, the tricky part is to parse and compare the date/time info of the files.
A simple dir dailynews.txt /S /O:-D does not work with subdirs.
So...
#echo off
cls
set base=H:\reports\test
set filename=dailynews.pdf
set current_date=19000101
set current_time=0000
set current_file=
::debug output
dir "%filename%" /S /O:-D
:: inspect each entry
for /F "usebackq" %%a in (`dir "%filename%" /S /B /O:-D`) do call :inspect "%%a"
:: all done, quit
goto :quit
:: subroutine for comparing current with actual newest entry
:inspect
echo %1
set _date=
set _time=
:: get comparable date time info
:: change to your regional date/time settings/locale! (german here)
:: maybe check SO for other locales
for /F "usebackq tokens=1,2,3,4,5 delims=.: " %%a in (`dir %1^|findstr "%filename%"`) do echo %%a %%b %%c %%d %%e&set _date=%%c%%b%%a&set _time=%%d%%e
:: we have to split in two components, otherwise it seems too big for comparing
if /I %_date% LSS %current_date% goto :eof
if /I %_time% LSS %current_time% goto :eof
:: this one is newer! set new values
set current_date=%_date%
set current_time=%_time%
set current_file=%1
goto :eof
:quit
set current_
Performance may get worse if you dont clean up the basedir at some time.

Saving Number of Lines in File as a Variable in Batch File

I have this really nice line in my batch file that tells me how many lines are in a file:
find /v /c "" C:\Users\c1921\mypath\myfolder\!$Unit!.txt
This is nice and gives me 31 for the particular file I'm working with. My problem is the file looks something like this:
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation. All rights reserved.
my_handled
219278
check
219276
control
219274
I want to be able to skip the first three lines entirely and then save the first value and then use the second value in my next command etc.
How do I save the number (e.g. 31) into a variable in my batch file?
On a hunch I tried setting a variable like so but it wasn't effective:
set "$testVar="""
echo !$testVar!
This command allows you to "save the number (e.g. 31) into a variable in my batch file":
for /F %%a in ('find /v /c "" ^< C:\Users\c1921\mypath\myfolder\!$Unit!.txt') do set numLines=%%a
This command allows you "to skip the first three lines entirely" and process the rest:
for /F "skip=3 delims=" %%a in (C:\Users\c1921\mypath\myfolder\!$Unit!.txt) do echo Processing: "%%a"
However, in my opinion this problem could be entirely avoided if the three first lines in the text file are supressed from the very beginning. I think this file is generated via a VBScript of JScript program that is executed this way:
cscript progname.vbs > C:\Users\c1921\mypath\myfolder\!$Unit!.txt
The first three lines in the text file may be avoided adding //nologo switch this way:
cscript //nologo progname.vbs > C:\Users\c1921\mypath\myfolder\!$Unit!.txt
#ECHO OFF
SETLOCAL
SET /a count=3
SET "first="
FOR /f "skip=3delims=" %%a IN (q25089468.txt) DO (
IF DEFINED first (CALL :show %%a) ELSE (SET "first=%%a")
)
ECHO count=%count%
GOTO :EOF
:show
ECHO first=%first% second=%1
SET /a count+=2
SET "first="
GOTO :eof
I used a file named q25089468.txt containing your data for my testing.
You appear to be asking two entirely different things - how to count the lines and how to skip the first 3, then deliver each succeeding pair to another process.

windows command line giving error on calculation

I found this nice little tidbit of code here: https://stackoverflow.com/a/5262637/2128987
#echo off
set starttime=%TIME%
set startcsec=%STARTTIME:~9,2%
set startsecs=%STARTTIME:~6,2%
set startmins=%STARTTIME:~3,2%
set starthour=%STARTTIME:~0,2%
set /a starttime=(%starthour%*60*60*100)+(%startmins%*60*100)+(%startsecs%*100)+(%startcsec%)
:TimeThis
robocopy /e /NFL /NDL /NJH /NJS /nc /ns /np folder%rndfolder% %drvltr%:\f%dirnew%\
set endtime=%time%
set endcsec=%endTIME:~9,2%
set endsecs=%endTIME:~6,2%
set endmins=%endTIME:~3,2%
set endhour=%endTIME:~0,2%
if %endhour% LSS %starthour% set /a endhour+=24
set /a endtime=(%endhour%*60*60*100)+(%endmins%*60*100)+(%endsecs%*100)+(%endcsec%)
set /a timetaken= ( %endtime% - %starttime% )
set /a timetakens= %timetaken% / 100
set timetaken=%timetakens%.%timetaken:~-2%
echo.
echo Took: %timetaken% sec.
As a standalone program it works great. I am using it with a robocopy command basically to determine how long it takes to write a file.
I add one extra variable in it because I want to keep the raw seconds for calculation purposes. So I add the extra line set timeraw=%timetaken%:
set /a timetaken= ( %endtime% - %starttime% )
***set timeraw=%timetaken%***
set /a timetakens= %timetaken% / 100
set timetaken=%timetakens%.%timetaken:~-2%
My batch file also uses setlocal enabledelayedexpansion
Well sometimes it does not properly calculate the "starttime" or "endtime". It's keeps it as the raw time in 08:30:22.35 type format and results in the error:
Invalid number. Numeric constants are either decimal (17),hexadecima (0x11), or octal (021)
Well obviously because it contains non-numeric characters like the : character.
My batch file goes in a continuous loop forever as I am using it to read, write, delete files and folders for a specific torture test condition.
Any idea why it would intermittently not calculate the starttime or endtime variables?
edit:
I made some changes to my overall script. I no longer need enabledelayedexpansion, cleaned up some if then statements, and simplified code a little. But I still occasionally get it where the starttime or endtime variables remain as the raw time format of HH:MM:SS.CS and causes error in calculation.
Old question, but there are probably blocks of parentheses and when you change a variable within parentheses then you need to use delayed expansion.
Run this and examine the differences.
#echo off
set a=nothing
if z==z (
set a=b
echo %a%
)
pause
setlocal enabledelayedexpansion
set a=nothing
if z==z (
set a=b
echo !a!
)
pause
Gee - a question nearly a year old, with no answer.
I'll assume that the problem has now been solved, so as a matter of record, I'd conclude that the
"sometimes it does not properly calculate" is because the hour/minute/second/hundredths will contain "08" or "09" which are not octal numbers.
The solution is
set /a startcsec=1%STARTTIME:~9,2% - 100
and repeat with each of the other 3 start time-segments; then repeat again with the end parts.
In addition, it could be that the hour is being presented with 0s suppressed. In this case, I'd suggest
set starttime=0%TIME: =%
set starttime=%startTIME:~-11%
set /a startcsec=1%STARTTIME:~9,2% - 100
where the first line prefixes the time with a '0', and replaces Space with [nothing]
the second selects just the last 11 characters of the result
and the last is the familiar form, using the resultant hh:mm:ss.cc format.
(obviously, the remainder of the substring-and-calculate method needs also to be implemented)

Variables in loops Dont Work, Batch

This is the new Script and it Still Doesn't Work
I Get The syntax of the command is incorrect.
on FOR /F "USEBACKQ tokens=*" %%A IN (TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command") DO (
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "C:\Windows\System32\tasks\at%num%" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "C:\Windows\System32\tasks\at!num! ^| FIND "Command"`) DO (
set var=%%A
ECHO %var%
SET /a num=%num%+1
PAUSE
)
GOTO:START
To understand your code, I'm going to break it down into logic first then try to solve it. Let me know if I miss a detail...
Set num var to 0
Begin :Loop
set num var to its current value ::NOT NEEDED - You've specified this prior to the GOTO
increment num var by +1
if myfolder\at* file exists then read at%num% and find a string then output that line to %tmp%\1.txt ::Need quotations on file location.
set F var to the line stored in %tmp%\1.txt
set F="%%F: =%%" ::Please explain what you are trying to do with this command.
set F to start on 10th character and remove the last 11 characters from the line.
echo the variable
If it doesn't exist, exit, but if it does return to :Loop
You should tell us what you are attempting. If it is as simple as saving a variable from a text file output, set F=<file.txt will work. If it didn't, then something happened prior to that command. Still... what is set F="%%F: =%%"?
Unless you are using a FOR loop variable, there is no need to use %% on each end of the variable.
If this were a FOR loop, it would look like this:
SETLOCAL ENABLEDELAYEDEXPANSION
set num=1
:START
IF NOT EXIST "myFolder\at%num%.txt" (GOTO:EOF)
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "myFolder\at%num%.txt" ^| FIND /i "string"`) DO (
PAUSE
SET var=%%A
ECHO !var!
PAUSE
SET var=!var: =!
ECHO !var!
PAUSE
SET var=!var:~10,-11!
ECHO !var!
PAUSE
SET /a num=!num!+1
ECHO !num!
PAUSE
)
GOTO:START
One good practice to check if commands are working, such as SET, insert an ECHO on the variable and a PAUSE right after each time you believe the variable should be changed. This will track what has changed on the variable so you can see if your command was correct and the changes were made.
I'd suggest using Batch's inbuilt function for loops, see here.
Conditionally perform a command for a range of numbers
Syntax
FOR /L %%parameter IN (start,step,end) DO command
Or maybe iterating over files in a folder would be better for what you are trying to do?
Loop through files (Recurse subfolders)
Syntax
FOR /R [[drive:]path] %%parameter IN (set) DO command
Or iterating over file contents?
Loop command: against a set of files - conditionally perform
a command against each item.
Syntax
FOR /F ["options"] %%parameter IN (filenameset) DO command
FOR /F ["options"] %%parameter IN ("Text string to process") DO command
This site has plenty of examples here which should point you in the right direction.
There are a few issues with your code, I've amended as follows to get the variable populated with the contents of the temp file.
set num=0
:Loop
set /a num=%num%+1
if exist "myFolder\at*" (
TYPE "myFolder\at%num%" | FINDSTR "\<Command\>" > "%temp%\1.txt"
set /P F=<"%TEMP%\1.txt"
Echo %F%
Pause
)
I don't know if this is the problem, but have you tried enabling:
setlocal enabledelayedexpansion
Then, inside the loop (or the IF(...)), you use !foo! to signify environment variables instead of %foo%.
See setlocal /? and set /? for more information.

syntax error on batch File to create a timestamp directory

I tried the script below to create a timestamp directory in one of my drives, for some reason is giving me a syntax error on the last string where it create the directory. See below.
:: Code begins....
pause
W:
pause
cd W:\VL2000_AMF\AMF_Archive
pause
for /F "tokens=1-4 delims=. " %%i in ('date /t') do (
set Day=%%i
set Month=%%j
set Year=%%k
)
pause
for /F "tokens=1-4 delims=: " %%i in ('time /t') do (
set Hour=%%i
set Minute=%%j
set Second=%%k
)
pause
md %1\%Year%-%Month%-%Day%
pause
:: Code ends....
I used the following on Windows 2000 and 2003 to get year, month, and day from the date command output. Unfortunately, I no longer have any XP systems to see if this will work there.
for /F "tokens=2-4 delims=/ " %%i in ('date /t') do (
echo "Day=%%i"
echo "Month=%%j"
echo "Year=%%k"
)
What is the format of "date /t" and "time /t" output on XP?
Are you sure your date is coming back as mm.dd.yyyy (separated by dots, and with the fields in the order you expect)? If the process's locale is not what you expect, you might be ending up with %Day% as something like 8/17/2010, which would cause md to report a syntax error as it tries to interpret /17 and /2010 as options.