appending date with filename using batch scripts - batch-file

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…

Related

getting syntax error when trying to run ren command

I am trying to build my software using cx_freeze for which I built a bat file that runs the build command so when the build is completed it generates build directory inside which there is another directory exe.win-amd64-3.6 containing the bundled code. inside which there is lib/scipy/spatial/cKDTree.cp36-win_amd64.pyd now this file has to be renamed as ckdtree.cp36-win_amd64.pyd for the build to run. I am trying to automate this by including rename in batch file but it's giving error.
I am trying to run rename command when build is completed but it's not working i get the error the syntax is incorrect. i tried to remove
%~dp0
even this didn't work
#ECHO OFF
Set "FRAS_Folder=%~dp0build_logs\FRAS"
If Not Exist "%FRAS_Folder%" MD "%FRAS_Folder%"
Call :Gen_Report_Name fras_logname
echo FileName : "%fras_logname%"
echo Absolute PathName : "%FRAS_Folder%\%fras_logname%"
REM Example save the result of this command with a log file into this folder
python setup.py build>"%FRAS_Folder%\%fras_logname%"
#REM rename the scipy.spatial.cKDtree file to scipy.spatial.ckdtree in lib/scipy/spatial
#REM rename the file cKDTree.cp36-win_amd64.pyd to ckdtree.cp36-win_amd64.pyd in lib/scipy/spatial
ren "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\cKDTree.cp36-win_amd64.pyd" "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\ckdtree.cp36-win_amd64.pyd"
pause & exit /b
:::::::::::::::::: FUNCTION :::::::::::::::::::
:Gen_Report_Name <file_with_date to be set>
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set "dt=%%a"
set datestamp=%dt:~0,8%
set timestamp=%dt:~8,6%
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 "stamp=%YYYY%%MM%%DD%_%HH%%Min%%Sec%"
Set "%1=%stamp%.log"
Exit /b
::------------------------------------------------------------------------------------
Kindly help me figure what's the issue!
You are using the wrong syntax for the ren command. See ren /?
The second filename must be a filename without path.
If you prefer to include the path for the second filename use the move command.
Windows is case insensitive so the files are having the same name. You will need to use an intermediate filename to change the case of the filename.
Try this:
ren "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\cKDTree.cp36-win_amd64.pyd" "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\ckdtree.cp36-win_amd64.tmp"
ren "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\ckdtree.cp36-win_amd64.tmp" "%~dp0build\exe.win-amd64-3.6\lib\scipy\spatial\ckdtree.cp36-win_amd64.pyd"

How to use gdal_calc in a batch file

I'm trying to create a mask file from several input images using gdal with a batch windows file. However, the system is sending me a error when I use the "!" on the comparison calc, and after the first round, all the variables had read as a string.
My code is the following:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET mypath=F:\my_in_path\
SET path_salida=F:\my_out_path\
FOR /F %%i IN ('DIR /B %mypath%*.tif') DO (
SET infile=%%i
SET outfile=!infile!
echo %mypath%!infile!
echo %path_salida%!outfile!
gdal_calc -A %mypath%!infile! --outfile %path_salida%!outfile! --calc="2*(A==0)+1*(A==0)" --NoDataValue=0 --quiet
)
As you've provided no feedback over half a day since my comment, here is an example to test and provide feedback on:
#Echo Off
Set "mypath=F:\my_in_path"
Set "path_salida=F:\my_out_path"
Set "calc_params=-A "%%A" --outfile "%path_salida%\%%~nxA" --calc="2*(A==0)+1*(A==0)" --NoDataValue=0 --quiet"
For %%A In ("%mypath%\*.tif") Do gdal_calc %calc_params%

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"

copying files from server to local automatically using batch command

I want to copy the particular logfile generated for each day in one of my server which i have access to my local daily automatically.
I prepared the batch commands as follows but didn't work as expected.
echo off
SET logfiles=\\PWWAS0015\UMS_Logs\server1\ums\service-*.log
rem set var = C:\Users\L068699\Desktop\test\src
echo %logfiles%
copy %logfiles% C:\Users\L068699\Desktop\test\
set yesterday = [DateTime]::Today.AddDays(-1).ToString("yyMMdd")
echo %yesterday%
pause
The problem is that I cana ble to extract all the logs but couldn't get the log which are like service-2015-04-17.log. How can I extract this kind of log which are one day behind i.e. if today is 2015-04-24 I should get the previous day log file service-2015-04-23.log
try like this:
pushd \\PWWAS0015\UMS_Logs\server1\ums\
rem set var = C:\Users\L068699\Desktop\test\src
::echo service-*.log
for /f "usebackq" %%a in (`"powershell (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"`) do set yesterday=%%a
echo %yesterday%
copy service-%yesterday%.log C:\Users\L068699\Desktop\test\
pause
Eventually you'll need NET command to map the network drivre:
NET USE \\PWWAS0015\UMS_Logs /PERSISTENT:YES
(put the net use before the pushd if it does not work)
Try this, may help you..
#echo
set source1="\\xxx"
set dest="\\yyy"
pushd %source1%
for /f "usebackq" %%i in (`"powershell (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')"`) do set yesterday=%%~i
copy "yourfilename %yesterday%.log" "%dest%"
popd

How to use batch job to add the file "create date" into all the files in a directory?

I have a folder that gets a new file added everyday to the folder with the same file name but incremental extension such as .001, .002, .003, etc. However, if there's no file within the folder it starts at .001 again.
The problem is they are all named the same and if I move them to another folder to archive them it would just overwrite the same file over and over again. I could create a folder each day with the date with only one file in it, but that seems a bit redundant.
Is there a way to look at the create date of each file and rename it to the create date?
I've gotten this far, but it looks like for this situation I have to use a static file name, how to loop through the entire directory?
SET filename = C:\test.001
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf
rename c:\test.001 C:\test_%filedatetime%.txt
move C:\*.txt C:\archive\
this provides the correct sort order:
#echo off &setlocal disableDelayedExpansion
set "startfolder=%userprofile%\test"
cd /d "%startfolder%"
for %%a in (*) do (
for /f "delims=." %%b in ('wmic datafile where "name='%startfolder:\=\\%\\%%~a'" get lastmodified^|find "."') do (
echo(ren "%startfolder%\%%~a" "%%~b.txt"
)
)
Remove echo to get it working.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "targetdir=c:\sourcedir"
SET "destdir=c:\destdir"
PUSHD "%targetdir%"
FOR %%a IN (*.*) DO (
SET "timestamp=%%~ta"
SET "timestamp=!timestamp:/=_!
SET "timestamp=!timestamp::=_!
SET "timestamp=!timestamp:.=_!
SET "timestamp=!timestamp:,=_!
SET "timestamp=!timestamp: =_!
ECHO MOVE "%%a" "%destdir%\%%~na.!timestamp!"
)
GOTO :EOF
This should work with any file in the nominated target directory where the name does not include ! or ^.
The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files. Append >nul to suppress report messages (eg. 1 file moved)
The gymnastics around timestamp are intende to replace /: with _ since these are illegal filename characters. Space., are similarly replaced - they're legal but often painful.
If you want the destination filename to be name.003.timestamp, remove the ~na from the destination name.
Try like this :
SET $path=The_path_who_contain_the_FILES
FOR /F "DELIMS=" %%f IN ('dir "%$path%" /a-d/b') DO (
SET filedatetime=%%~tf
move "%%~dpnxf" "C:\archive\test_%filedatetime%.txt")

Resources