Give Date Time on Bat File & Dynamic Path - batch-file

I Hae Create BAT File
#ECHO OFF
"C:\Program Files\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /FILE "D:\New folder (2)\xslttosql\SSIS-BSMS\SSIS-BSMS\SSIS-BSMS\Package6.dtsx" /REP P >> "D:\TRX_Value.log"
exit
but i Want to make the Output which D:\TRX_Value.log path Changed Dynamically and give time information on the file name like D:\TRX_Value-20130307-144650.log which mean 2012/03/07 14:46:50
So is it possible? What kind of script should I write?

Dealing with dates is somewhat tricky in BAT files.
A simple solution is to use WMIC LocalTime command which returns the current date and time in a convenient way to directly parse it with a FOR command. Try something similar to this:
#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 DT=%%F*10000+%%D*100+%%A
SET /A TM=%%B*100+%%C
SET FDT=%DT%-%TM%
)
ECHO "c:\progs\dtexec" /FILE "d:\fldr\pack.dtsx" /REP P "d:\logs\tr%FDT%.log"
check the result and correct the execution line to fit your reqs

I like PA's suggestion to use WMIC, but there is a much simpler WMIC implementation.
The OS alias has the localDateTime property in almost the exact format you want:
YYMMDDhhmmss.ffffff-zzz
where ffffff is fractional seconds, and zzz is time zone information. Simple substring operations provide the desired date and time format.
#echo off
setlocal
set "ts="
for /f "skip=1" %%A in ('wmic os get localDateTime') do if not defined ts set "ts=%%A"
... your exe call ... >>"D:\TRX_Value-%ts:~0,8%-%ts:~8,6%.log"

Just because I like a challenge, here's a batch script / JScript hybrid script that'll format your timestamp the way you want. Save this with a .bat extension.
#if (#X)==(#Y) #end /* (batch + jscript hybrid script init)
:: *** Batch script *****
#echo off
setlocal
for /f %%I in ('cscript /nologo /e:jscript "%~f0"') do set "ts=%%I"
"C:\Program Files\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /FILE "D:\New folder (2)\xslttosql\SSIS-BSMS\SSIS-BSMS\SSIS-BSMS\Package6.dtsx" /REP P >> "D:\TRX_Value-%ts%.log"
exit /b
:: *** JScript script *****/
var d = new Date();
WScript.echo(d.getFullYear() + /\d{2}$/.exec('0' + (d.getMonth() + 1)) + /\d{2}$/.exec('0' + d.getDate()) + '-'
+ /\d{2}$/.exec('0' + d.getHours()) + /\d{2}$/.exec('0' + d.getMinutes()) + /\d{2}$/.exec('0' + d.getSeconds()));
(dbenham is a master at this sort of stuff.)

Echo's the date and time into 2 temp files, then parses them into correct format, and uses them in your command.
#ECHO OFF
Set CURRDATE=%TEMP%\CURRDATE.TMP
ECHO %DATE% > %CURRDATE%
Set CURRTIME=%TEMP%\CURRTIME.TMP
ECHO %TIME% > %CURRTIME%
Set PARSEDATEARG="eol=; tokens=1,2,3,4* delims=/, "
Set PARSETIMEARG="eol=; tokens=1,2,3,4,5* delims=:,., "
For /F %PARSEDATEARG% %%i in (%CURRDATE%) Do SET YYYYMMDD=%%k%%j%%i
For /F %PARSETIMEARG% %%i in (%CURRTIME%) Do SET HHMMSS=%%i%%j%%k
"C:\Program Files\Microsoft SQL Server\100\DTS\Binn\dtexec.exe" /FILE "D:\New folder (2)\xslttosql\SSIS-BSMS\SSIS-BSMS\SSIS-BSMS\Package6.dtsx" /REP P >> "D:\TRX_Value-%YYYYMMDD%-%HHMMSS%.log" exit

Related

Batch File - Create Zip file with Command Line using the first part of the first file name

I have a folder of PDF files that have a consistent naming convention. I want to create a zip file of these PDF files but named the zip file using the portion of the file that is before the # -- all of the files are the same in the front (it is the NTID of the user that created the pdf files).
As an example these are what the files might look like in the PDF output folder (there could be 100 files all that start with the same UserID before the #:
UserID#Carlos+Alberto+Mafra-+bribery-2019-05-16
UserID#MAJELA+HOSPITALAR+LTDA-+bribery-2019-05-16
(Ideally, I would also want the current date appended to the zip file)
The zip should be called UserID-2019-05-16.zip based on the example above.
This is the code I am trying to use but not having success...
I created a batch script using others suggestions for each step. but can't get it to work end to end.
FOR %%F IN ("C:\Users\SA-JJC-HCC_Ops\OneDrive - JNJ\workflows\TPIGoogle\pdf\*.pdf") DO (
set filename=%%F
goto next
)
:next
echo "%filename%"
set zipfile=%filename%
for /f "tokens=1 delims=#" %%a in ("%zipfile%") do (
)
cd "C:\Program Files\7-Zip\"
7z.exe" a "C:\Users\SA-JJC-HCC_Ops\JNJ\HCC&P Alteryx - Documents\EPiC\GoogleSearches\zip\" && %zipfile% && ".zip" "C:\Users\SA-JJC-HCC_Ops\OneDrive - JNJ\workflows\TPIGoogle\pdf\*.pdf"
One zip file with all the PDFs that are using the first part of the string from the file names in the PDF folder.
#ECHO OFF
SETLOCAL enabledelayedexpansion
SET "sourcedir=U:\sourcedir\t w o"
SET "destdir=U:\destdir"
FOR /f "tokens=1*delims=#" %%a IN (
'dir /b /a-d "%sourcedir%\*#*-????-??-??.pdf" '
) DO (
SET "pre=%%~a"
SET "post=%%~nb"
SET "post=!post:~-10!"
IF DEFINED post ECHO "C:\Program Files\7-Zip\7z" a "%destdir%\!pre!-!post!.zip" "%sourcedir%\%%~a#%%~b"
IF NOT DEFINED post ECHO SKIP "%%~a#%%~b"
)
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances.
I used the variablenames pre and post to ensure that the names used in this process are not keywords like the more logical date.
Read a list of all filenames matching the pattern *#*-????-??-??.pdf in the source directory, tokenising on #. Assign the userid to %%a and thence to pre and the "name" part of the dregs of the actual filename to post, then select only the last 10 characters of post using delayed-expansion.
There is an opportunity here to further process post to check whether it truly fits the pattern for a date, if that is required. That routine may return post either unmolested or empty. If it's not empty then construct the required 7z command (you may wish to add -tzip) and echo this for verification - remove the echo to actuate the 7z compression. If post is emptied by a pattern-checking routine, then the filename will simply be reported as having been skipped.
If it is indeed current date you want to append to the end of the zip file, then we need to get the non locale dependent date and time. This will then copy each of the pdf files that starts with UserID to a zip with a date of the day you run the script UserID-2019-05-17 :
#echo off
set "outDir=C:\Users\SA-JJC-HCC_Ops\JNJ\HCC&P Alteryx - Documents\EPiC\GoogleSearches\zip\"
set "inDir=C:\Users\SA-JJC-HCC_Ops\OneDrive - JNJ\workflows\TPIGoogle\pdf\"
for /f "tokens=1,2 delims==" %%i in ('wmic os get LocalDateTime /VALUE') do (
if ".%%i."==".LocalDateTime." set mydate=%%j
)
set mydate=%mydate:~0,4%-%mydate:~4,2%-%mydate:~6,2%
for %%a in (*.pdf) do for /f "delims=#" %%i in ('dir /b /a-d %%a') do (
"C:\Program Files\7-Zip\7z" a "%outDir%%%i-%mydate%.zip" "%inDir%%%~a"
)
If in fact you want to append the date of the filename instead (In other words create Zip files for each file with a different date as well as matching userid):
#echo off
setlocal enabledelayedexpansion
set "outDir=C:\Users\SA-JJC-HCC_Ops\JNJ\HCC&P Alteryx - Documents\EPiC\GoogleSearches\zip\"
set "inDir=C:\Users\SA-JJC-HCC_Ops\OneDrive - JNJ\workflows\TPIGoogle\pdf\"
for %%a in (*.pdf) do for /f "tokens=1,* delims=#" %%i in ('dir /b /a-d %%a') do (
set fdate=%%~nj
set fdate=!fdate:~-10!
echo "C:\Program Files\7-Zip\7z" a "%outDir%%%i-!fdate!.zip "%inDir%%%~a"
)

appending date with filename using batch scripts

I am trying to set a housekeeping for different type of file. PFB scenario.
I have below set of files in a network path(\NAS.domain.local\data\Arasan)
test.sql
test1.txt
test2.log
I am trying to rename the files as shown below and move the files to .\Archive\ directory
Test_15-12-2016_151428.sql
Test1_15-12-2016_151428.txt
Test_15-12-2016_151428.log
([Filename]_DD-MM-YYYY_HHMISS.[ext])
I have built the below batch script.
#echo ON
SET Log_Path=\\NAS.domain.local\data\Arasan
SET Script_Path=C:\Scripts
REM ###########################################REM
REM ## Do make any changes to the text below ##REM
REM ###########################################REM
cd %Script_Path%
pushd %Log_Path%
dir /b /a-d > %Script_Path%\list.txt
set HH=%TIME:~0,8%
for /F %%A in (%Script_Path%\list.txt) do (
setlocal EnableExtensions EnableDelayedExpansion
set ffname=%%A
set "fname=%%~nA"
set "fext=%%~xA"
ren !ffname! !fname!_%DATE%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%!fext!
endlocal
)
del %Script_Path%\list.txt
move *.* Archive\
popd
exit
Now my issue is it is working perfectly in my machine but when I transfer this to server and execute. It is
throwing "The syntax of the command is incorrect." Error.
And it is moving the files without renaming. As for as i know, file name and extension is not being assigned to the variable properly in below part
set ffname=%%A
set "fname=%%~nA"
set "fext=%%~xA"
Server OS: Windows server 2008 R2 Standard(SP1)
Can anyone please help me. Thanks a lot.
Here is the part of the code you should be using to get a consistent date and time output:
For /F "Skip=1" %%A In ('WMIC OS GET LocalDateTime') Do For %%B In (%%~nA
) Do Set "DTS=%%B"
Set "DTS=_%DTS:~6,2%-%DTS:~4,2%-%DTS:~,4%_%DTS:~-6%"
Echo( [%DTS%]
Pause
Just incorporate this into the rest of your code…

Batch: search for files with certain extension, owner, fullpath and last write access and output in CSV

I'm trying to create a CSV with fullpath\filename, file owner and last write access (modification date) of all txt and html files from all hard drives of a data server.
Here's what I got so far:
set pgm=%~n0
set log=%~dpn0.log
set host=%COMPUTERNAME%
set csv=%host%.csv
set dir=D:\BME
if not exist "%csv%" type nul>"%csv%"
for /f "delims=;" %%a in ('dir /b/s %dir%\*.txt, %dir%\*.html') do (
>>%csv% echo "%%a"
)
That outputs the path + filename of all found txt and html files of a certain folder in a CSV. I tried this command to get the hard drives:
wmic logicaldisk where drivetype=3 get caption
But I can't get my head around how to store that in a variable or file and loop through it and also retrieve the owner and last modification date and put it into a new column of the csv file.
I can't get my head around how to store that in a variable
Use the following batch file.
GetDrives.cmd:
#echo off
setlocal enabledelayedexpansion
rem skip=1 to remove the header
rem findstr to remove blank lines
for /f "skip=1" %%d in ('wmic logicaldisk where drivetype^=3 get caption ^| findstr /r /v "^$"') do (
set _drive=%%d
echo !_drive!
)
endlocal
Notes:
Be careful when using drivetype=3 as I have a removable drive of type 3. In the below output C: is a fixed hard disk and F: is a removable external USB drive.
Replace echo !_drive! as appropriate with a modified version of your existing code.
Example Output:
F:\test>GetDrives
C:
F:
F:\test>
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
for /f - Loop command against the results of another command.
wmic - Windows Management Instrumentation Command.
DavidPostill answered how-to store wmic logicaldisk … output in a variable;
to retrieve file last modification date: use echo "%%a","%%~ta" in your script using %~t Parameter Extension;
to retrieve file owner: echo "%%a","%%~ta","!_owner!" where _owner variable comes from getRealOwner subroutine based on modified schletti2000's answer Get ownership information from command line by using wmic.
The script:
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "pgm=%~n0"
set "log=%~dpn0.log"
set "host=%COMPUTERNAME%"
set "csv=%host%.csv"
set "dir=D:\BME"
set "dirmask=%dir%\*.txt, %dir%\*.html"
rem if not exist "%csv%" type nul>"%csv%"
>"%csv%" (
for /f "delims=;" %%a in ('dir /b/s %dirmask% 2^>NUL') do (
set "_fFullPath=%%~a"
set "_fLastWrite=%%~ta"
set "_fOwner="
call :getRealOwner
SETLOCAL EnableDelayedExpansion
echo "!_fFullPath!","!_fOwner!","!_fLastWrite!"
ENDLOCAL
)
)
)
type "%csv%"
goto :continue
:getRealOwner
SET "ESCAPED=%_fFullPath:\=\\%"
SET "UNDELIMITED="
for /F "skip=2 delims=" %%g in ('
wmic path Win32_LogicalFileSecuritySetting where Path^="%ESCAPED%" ^
ASSOC /RESULTROLE:Owner /ASSOCCLASS:Win32_LogicalFileOwner ^
/RESULTCLASS:Win32_SID 2^>NUL
') do (
SET "UNDELIMITED=%%g"
call :process_wmioutput
)
if NOT defined UNDELIMITED set "_fOwner=???"
exit /B
:process_wmioutput
SET "DELIMITED=%UNDELIMITED: =•%"
FOR /F "delims=• tokens=10,12" %%G in ("%DELIMITED%") DO set "_fOwner=%%H\%%G"
exit /B
:continue
I used next settings to demonstrate various output:
set "dir=D:"
set "dirmask=%dir%\loc*.vbs %dir%\bcd*.log %dir%\act*.xsl %dir%\diag*.xml %dir%\chec*.csv"
Output - non-privileged cmd window:
==> D:\bat\SO\39034430.bat
"D:\odds and ends\tempx\links\testDJ\LocUsers.vbs","mypc\user","25.12.2014 00:13"
"D:\tempWin\ActivityLog.xsl","NT AUTHORITY\SYSTEM","24.02.2016 13:12"
"D:\tempWin\CompatTelemetryLogs\diagerr.xml","???","12.08.2015 03:17"
"D:\tempWin\CompatTelemetryLogs\diagwrn.xml","???","12.08.2015 03:17"
"D:\test\check_acl.csv","BUILTIN\Administrators","06.03.2016 14:28"
Output - privileged (run as administrator) cmd window:
=ADMIN=> D:\bat\SO\39034430.bat
"D:\odds and ends\tempx\links\testDJ\LocUsers.vbs","mypc\user","25.12.2014 00:13"
"D:\tempWin\ActivityLog.xsl","NT AUTHORITY\SYSTEM","24.02.2016 13:12"
"D:\tempWin\CompatTelemetryLogs\diagerr.xml","NT AUTHORITY\SYSTEM","12.08.2015 03:17"
"D:\tempWin\CompatTelemetryLogs\diagwrn.xml","NT AUTHORITY\SYSTEM","12.08.2015 03:17"
"D:\test\check_acl.csv","BUILTIN\Administrators","06.03.2016 14:28"

batch - File last modification time with seconds

I want to know when a file has been modified for the last time.
I can get these infos using the following batch script:
FOR %%i IN (myfile) DO SET modif_time=%%~ti
The problem is that I need the second of the last modification and the command %~t returns the date and the time with only hours and minutes.
I can only check the seconds by manually viewing the "property window" file by file.
How can I get the time with seconds in batch?
In Windows 7 and forward (or via Resource Kit for XP) you can use forfiles for this. Something like:
forfiles /m *.* /c "cmd /c ECHO The last modified date of: #file is: #ftime"
In a directory with the following files:
myTest.txt
myTest2.txt
I get:
The last modified date of: "myTest.txt" is: 13:21:07
The last modified date of: "myTest2.txt" is: 13:21:20
wmic datafile where name="FileName" get LastModified
FileName must contain the full path with double backspaces.
Sorting example (recent first):
for /f "delims=" %a in ('wmic datafile where "drive='c:' and path='\\windows\\'" get LastModified^,Name /format:table^|find ":"^|sort /r') do #echo %a
wmic datafile where "drive='c:' and path='\\windows\\'" get "Last Modified",Name
You can embed a small JScript in the batch file to get the last modified epoch:
#if (#a==#b) #end /*
#echo off
SetLocal EnableDelayedExpansion
set EPOCH=0
FOR /F "delims=" %%D in ('cscript /nologo /e:jscript "%~f0" "%1"') do (
set EPOCH=%%D
)
echo Last modified (epoch-seconds): !EPOCH!
goto :eof
*/
var fs = new ActiveXObject("Scripting.FileSystemObject");
var filename = WSH.Arguments(0)
var millis = -1
if (fs.FileExists(filename))
{
var file = fs.GetFile(filename);
millis = Date.parse(file.DateLastModified) / 1000;
}
WSH.Echo(millis);
The /* */ will comment out the batch script while running as a JScript, and the #if (#a==#b) #end and goto :eof will skip the JScript while running as a batch script
>epoch.bat epoch.bat
Last modified (epoch-seconds): 1533282229
>epoch.bat "epoch.bat"
Last modified (epoch-seconds): 1533282229
>epoch.bat notareal.file
Last modified (epoch-seconds): -1

How can I output weekday and month in batch (log files)?

I'm trying to setup 7zip for automated backups but I'm having trouble with output file names.
I tried using the %date% command but it just made 2 directories within my backup.
C:\Users\Desktop\Sun 11\07\2010.7z
How can I make it just log the day and month?
C:\Users\Desktop\Sun 11-07-2010.7z
Try
7z a %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.7z *.* for (YYYY-MM-DD)
or
7z a %DATE:~7,2%-%DATE:~4,2%-%DATE:~-4%.7z *.* for (DD-MM-YYYY)
(*.* is the mask for the files to back up)
Are you using a bat-file? Look here http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/
You can use WMI to get your date details in a specific format. The problem with the output from date (and the %date% environment variable) is that it's very locale-specific.
If you execute:
wmic path win32_localtime get day^,month^,year^ /format:csv
you will see the output you need to process.
The following script will get you the yyyy-mm-dd format that you need (using the day of the week as the primary sort key is not a good idea):
#echo off
for /f "skip=2, tokens=2-4" delims=," %%a in ('wmic path win32_localtime get day^,month^,year^ /format:csv') do (
set /a ymd = 10000 * %%c + 100 * %%b + %%a
)
set ymd=%ymd:~0,4%-%ymd:~4,2%%ymd:~6,2%
echo %ymd%

Resources