batch file creates log file with incorrect log name - batch-file

Batch file creates log file with incorrect log name.
I am running on Windows 10
There are two batch files.
Bat File 1 sets up some these variables and calls the 2nd batch file.
V_FILE_DIR, V_BAT_FILE_DIR, V_FILE_NAME, V_FILE_DAYS_OLD, V_LOG_FILE_NAME.
Bat File 2 accepts the environment variables sent by the Bat File 1.
and uses them to look for files in a directory that are greater than N days old.
It creates a log file with the number of files it is going to delete and a list of the files that will be deleted.
then it deletes the files.
These batch files work perfectly when I execute them from Windows Explorer.
When they are executed by Windows Scheduler they delete the files but the log file is given the incorrect log name and the deleted file are not listed inside the log file.
: ---- remove_MVIEW_SERVICE_BI_PART_MASTER_old_files.bat
: Bat file #1
#set V_FILE_DIR="C:\Users\khughes\Desktop\KCH_WAKA-PDMDB-V01_WINDCHILL_PROD\Oracle\0BAT\MVIEW_SERVICE_BI_PART_MASTER"
#set V_BAT_FILE_DIR="C:\Users\khughes\Desktop\KCH_WAKA-PDMDB-V01_WINDCHILL_PROD\Oracle\0BAT\REMOVE_OLD_FILES"
#SET V_FILE_NAME="*.LOG"
#SET V_FILE_DAYS_OLD=14
#SET V_LOG_FILE_NAME=MVW_SRVCE_BI_PRT_MSTR
call %V_BAT_FILE_DIR%\remove_old_files.bat %V_FILE_DIR% %V_BAT_FILE_DIR% %V_FILE_NAME% %V_FILE_DAYS_OLD% %V_LOG_FILE_NAME%
: Bat file #2
#IF [%1]==[] goto NOPARM
:---> Set variables section
#set V_FILE_DIR=%1%
#set V_BAT_FILE_DIR=%2%
#SET V_FILE_NAME=%3%
#SET V_FILE_DAYS_OLD=%4%
#SET V_LOG_FILE_NAME=%5%
#set V_HOUR=%time:~0,2%
#if "%V_HOUR:~0,1%" == " " set hour=0%V_HOUR:~1,1%
:echo hour=%V_HOUR%
#set V_MIN=%time:~3,2%
#if "%V_MIN:~0,1%" == " " set min=0%V_MIN:~1,1%
:echo min=%V_MIN%
#set V_SECS=%time:~6,2%
#if "%V_MIN:~0,1%" == " " set secs=0%V_MIN:~1,1%
:echo V_SECS=%V_MIN%
#set V_MONTH=%date:~-10,2%_%date:~-7,2%_%date:~-4,4%
#set V_YEAR=%date:~-4%
#set V_DATE_TIME=%V_MONTH%__%V_HOUR%_%V_MIN%_%V_SECS%
:---> Code section
#echo off
set "File=tmpfile"
set /a count=0
SETLOCAL enabledelayedexpansion
forfiles /p %V_FILE_DIR% /m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% /c "cmd /c echo The extension of #file is 0x09#ext") >> tmpfile
for /F "tokens=* delims=" %%a in ('Type "%File%"') do (
Set /a count+=1
Set "output[!count!]=%%a" )
IF %count% EQU 0 (Echo No files found to delete) ELSE (Echo %count% files were found to delete)
set V_NEWFILENAME=%V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo "--->*******************************************" >> %V_NEWFILENAME%
echo "--->* %count% files deleted on %V_DATE_TIME% *" >> %V_NEWFILENAME%
echo "--->*******************************************" >> %V_NEWFILENAME%
forfiles -p %V_FILE_DIR% -m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% -c "cmd /c echo del #path" >> %V_NEWFILENAME%
forfiles -p %V_FILE_DIR% -m %V_FILE_NAME% -d -%V_FILE_DAYS_OLD% -c "cmd /c del #path"
del %V_BAT_FILE_DIR%\tmpfile
goto exit1
:NOPARM
echo '******* Parameter Value Missing *******' >> V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
:exit1
echo . >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '***********************' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '******* Exiting *******' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
echo '***********************' >> %V_BAT_FILE_DIR%\remove_%V_LOG_FILE_NAME%_%V_DATE_TIME%.log
EXIT /b

Related

How to record purged files into a log file

I am using the following code in a batch file to purge any files older than 60 days. I would like the log file to print the file names that have been purged for record keeping purposes. How can I do that?
setlocal EnableDelayedExpansion
set logpath=C:\Temp\Archive
REM if not exist %logpath% md %logpath%
set FILEAGE=60
set archlog=%logpath%\Accurate_ARCHIVE.txt
set inputdir=C:\Temp
REM Set the date
FOR /f "tokens=2,3,4 delims=/ " %%a in ('date/t') do (set DD=%%a) & (set MM=%%b) & (set YYYY=%%c)
REM * Purge files older than %FILEAGE% days from disk.
forfiles /p "%inputdir%" /s /m *.* /d -%FILEAGE% /c "cmd /c del #path"
ECHO Folder %inputdir% was processed on %DD%-%MM%-%YYYY% >> %archlog%
ECHO Files older than %FILEAGE% days have been purged. >> %archlog%
exit %errorlevel%
I am expecting the log file to print the names of the files purged.
Add echo #path to the del #path command.
Something like below (untested).
"cmd /c (del #path) & (>> %archlog% echo #path)"
A more advanced version incorporating comments by Aschipf and Compo.
The 0x22 puts doupble quots around the filename and prevents problems with space and other special characters in the filename.
Deleted files are reported and files that could not be deleted are reported prefixed with NOT DELETED:.
"cmd /c if #isdir==FALSE (del #path) & (>> 0x22%archlog%0x22 if exist #path (echo NOT DELETED: #path) else (echo #path))"

How do I count files in 2 different directories and do a compare using batch file?

I am trying to compare the number of files on a local folder to that of the source folder which is in a server.
I have the following lines in a batch file below but i always get the same value for both no matter what.
#for /f %%a in ('2^>nul dir "%local_folder%" /a/b/-o/-p/s^|find /v /c ""') do set n=%%a
echo Total files in Local Folder: %n%
pause
#for /f %%a in ('2^>nul dir "%source_folder%" /a/b/-o/-p/s^|find /v /c ""') do set m=%%a
echo Total files in Source Folder: %m%
pause
if %n%==%m% (copy update_folder local_folder.\ && goto end) else (goto copy_all_files)
pause
I am getting the same value for when I try to count the files in the separate locations. I only want to count the visible files with extension *.wav on each folder.
UPDATE: RESOLUTION I found is below,
:file_count_chck
set folder_cf=".\folder-A\*.wav"
set folder_lib="\\folder-B\*.wav"
dir %folder_cf% > A.txt
dir %folder_lib% > B.txt
set count_cf=0
for /f %%x in (A.txt) do set /a count_cf+=1
set count_lib=0
for /f %%y in (B.txt) do set /a count_lib+=1
set data_lines=5
set /A count_cf = %count_cf%-%data_lines%
set /A count_lib = %count_lib%-%data_lines%
echo.
echo Checking Sound folder...
echo Sound files on CF card = %count_cf%
echo Sound files on library = %count_lib%
del "A.txt" "B.txt"
set /a difference_count=%count_lib%-%count_cf%
if %difference_count% EQU 0 (echo Ok && goto wav_update) else (echo Detected missing files and correcting && goto copy_all_wav)
Hope someone finds this useful.

Folder list and its sizes

I have a parent folder which contains more than 100 sub-folders. I want a text file which contain sub-folders and their size. Could you please help me to build the batch program?
Only for the files name without the size you can use this code-
dir *.* /b /s >> C:\ListOfFile.txt
Change your "C:\" path to whenever you want to save your file.
Although you did not show any effort to try it on your own, I decided to help you, because the task might not be that particularly trivial to accomplish...
Have you ever seen the output of dir /S (the command to list files in a specified directory and all its sub-directories)? It summarises the total count of files at the end, including also the overall size:
D:\TEMP>dir /S /-C
Volume in drive D is DATA
Volume Serial Number is XXXX-XXXX
Directory of D:\TEMP
2016/05/12 12:00 <DIR> .
2016/05/12 12:00 <DIR> ..
0 File(s) 0 bytes
Total Files Listed:
0 File(s) 0 bytes
2 Dir(s) ?????????? bytes free
So we can do a dir /S command for every directory at the given location, capture its output using a for /F loop, retrieve the line before the last one and extract the size value.
The following pure batch-file script -- let us call it folder_sizes.bat -- does exactly these steps:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Get provided arguments:
set "FOLDER=%~1"
set "LOG=%~2"
rem // Check provided arguments:
if not defined LOG set "LOG=con"
setlocal EnableDelayedExpansion
>&2 (
if not defined FOLDER (
echo(ERROR: no directory specified!
exit /B 1
) else if not exist "!FOLDER!\" (
rem /* (trailing "\" to check for directory) */
echo(ERROR: directory not found!
exit /B 1
)
)
rem // Process all sub-directories of given directory:
> "!LOG!" (
for /D %%D in ("!FOLDER!\*") do (
for /F "skip=10 tokens=3" %%F in ('
dir /S /-C "%%~fD"
') do (
set "BYTES=!VALUE!"
set "VALUE=%%F"
)
setlocal DisableDelayedExpansion
set "ITEM=%%~nxD"
setlocal EnableDelayedExpansion
rem // Return name and size of sub-directory:
echo(!ITEM! !BYTES!
endlocal
endlocal
)
)
endlocal
endlocal
exit /B
To run this script on a certain directory -- for instance D:\TEMP -- and to write the log data to the file folder_sizes.log in the current directory, use the following command line:
folder_sizes.bat "D:\TEMP" ".\folder_sizes.log"
In the script, delayed expansion is toggled in order to avoid problems with (sub-)directories containing exclamantion marks (!) in their names.
Notice that the output of the dir /S command is language-dependent, so the script might not provide the expected results on systems other than English ones. In such situations, the option string "skip=10 tokens=3" of the for /F loop, particularly the token option, needs to be adapted accordingly.
This code can did the trick :
#echo off
Title Get Size of Folder and its subfolders
set "Folder=C:\temp"
Set Log=Folder_Size.txt
(
echo The size of "%Folder%" is
Call :GetSize "%Folder%"
)> "%Log%"
For /f "delims=" %%a in ('Dir "%Folder%" /AD /b /s') do (
(
echo The size of "%%a" is
Call :GetSize "%%a"
)>> "%Log%"
)
start "" "%Log%"
::***********************************************************************
:GetSize
(
echo wscript.echo GetSize("%~1"^)
echo Function GetSize(MyFolder^)
echo Set fso = CreateObject("Scripting.FileSystemObject"^)
echo Set objFolder= fso.GetFolder(MyFolder^)
echo GetSize = FormatSize(objFolder.Size^)
echo End Function
echo '*******************************************************************
echo 'Function to format a number into typical size scales
echo Function FormatSize(iSize^)
echo aLabel = Array("bytes", "KB", "MB", "GB", "TB"^)
echo For i = 0 to 4
echo If iSize ^> 1024 Then
echo iSize = iSize / 1024
echo Else
echo Exit For
echo End If
echo Next
echo FormatSize = Round(iSize,2^) ^& " " ^& aLabel(i^)
echo End Function
echo '*******************************************************************
)>%tmp%\Size.vbs
Cscript /NoLogo %tmp%\Size.vbs
Del %tmp%\Size.vbs
Exit /b
::***********************************************************************

How to edit hosts file using a batch file (check for line, add if not existing and delete if existing)?

I have a batch script to add several lines to my hosts file to block certain websites on my computer.
I would like to use the batch script in such a way that when I run my example.bat, it first checks if the lines to add exist, and if they don't then add them. But the batch file should delete the lines in case of existing already in hosts file. In other words the batch file should toggle the presence of the lines in the hosts file.
How could this be done?
Here is what I have so far. All it does is adding the lines.
#echo off
:: BatchGotAdmin
::-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SystemRoot%\system32\cacls.exe" "%SystemRoot%\system32\config\system"
REM --> If error flag set, we do not have administrator privileges.
if not errorlevel 1 goto gotAdmin
echo Set UAC = CreateObject^("Shell.Application"^) >"%temp%\getadmin.vbs"
set params=%*
if defined params set params=%params:"=""%
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
::--------------------------------------
#echo off
set hostspath=%SystemRoot%\System32\drivers\etc\hosts
echo 127.0.0.1 www.example1.com >> %hostspath%
echo 127.0.0.1 www.example2.com >> %hostspath%
echo 127.0.0.1 www.example3.com >> %hostspath%
exit
A pure batch code with explanatory comments:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "hostspath=%SystemRoot%\System32\drivers\etc\hosts"
rem Initialize the array of our hosts to toggle
for %%a in (
"127.0.0.1 www.example1.com"
"127.0.0.1 www.example2.com"
"127.0.0.1 www.example3.com"
) do (
set /a numhosts+=1
set "host!numhosts!=%%~a"
)
>"%hostspath%.new" (
rem Parse the hosts file, skipping the already present hosts from our list.
rem Blank lines are preserved using findstr trick.
for /f "delims=: tokens=1*" %%a in ('%SystemRoot%\System32\findstr.exe /n /r /c:".*" "%hostspath%"') do (
set skipline=
for /L %%h in (1,1,!numhosts!) do (
if "%%b"=="!host%%h!" (
set skipline=true
set found%%h=true
echo - %%b 1>&2
)
)
if not "!skipline!"=="true" echo.%%b
)
for /L %%h in (1,1,!numhosts!) do (
if not "!found%%h!"=="true" echo + !host%%h! 1>&2 & echo !host%%h!
)
)
move /y "%hostspath%" "%hostspath%.bak" >nul || echo Can't backup %hostspath%
move /y "%hostspath%.new" "%hostspath%" >nul || echo Can't update %hostspath%
endlocal
pause

.bat for batch rename to increment numbers in fname

I have a large folder of .cbr's, and I'm renaming them by issue number to correctly order them. What do I need to include in the ren line to have each file increment the number in the file name via windows command prompt? I'll be doing this frequently so I'll make this a .bat file.
For example, where n = initial number and m = final number: n.cbr, (n+1).cbr, ..., (m-1).cbr, m.cbr
The .bat thusfar:
ren *.cbz *.cbr
ren *.cbr <increment numbers n through m>.cbr
Alternatively, how do I trim each file name so that only the numbers are left before the extension? (from issue1.cbr to 1.cbr) via either a .bat or script host file?
Try this batch script.
#echo off
setlocal enabledelayedexpansion
set /a count=0
for /f "tokens=*" %%a in ('dir /b /od *.cbr') do (
echo ren "%%a" !count!.cbr
set /a count+=1
)
It renames all the files with a incremental counter. The order of the files is preserved with the /OD option of the DIR command, that sorts the files list by its modified timestamp.
After careful testing, remove the ECHO command.
For more information, read HELP DIR, HELP SET and HELP FOR.
:: REN-sec.cmd ==> Rename files to increment numbers
:: Inspired on -> http://stackoverflow.com/questions/6322329#6324312
:: - (cX) 2017 adolfo.dimare#gmail.com
:: -> CAVEAT: Works on CURRENT directory!
:: - Tested on Win10 64bits
#echo off
if (%1)==() goto _help
if (%1)==(/?) goto _example
setLOCAL EnableDelayedExpansion
rem EnableExtensions
if (%1)==(/r) goto _recursive
if (%1)==(/R) goto _recursive
goto _current_dir
:_recursive
for /d %%A in (*.*) do (
cd "%%~A"
call %~dpnx0 %1 %2 %3 %4
rem echo returning -^> call %~dpnx0 %1 %2 %3 %4
cd ..
)
shift
goto _current_dir
:_current_dir
set /a _count=0
for %%A in (%1) do (
set /a _count+=1
rem Execute several times to rename 'crazy' left overs...
FOR /L %%C IN (1,1,2) DO (
if exist "%~2!_count!%~3%%~xA" call :skip_count %1 %2 %3 %AA
if exist "%%~A" if not exist "%~2!_count!%~3%%~xA" ren "%%~A" "%~2!_count!%~3%%~xA"
)
if exist "%%~A" echo EXISTS "%%~A"
REM if not exist "%~2!_count!%~3%%~xA" echo MISSING %~2!_count!%~3%%~xA
)
goto _out
:skip_count
set /a _count+=1
if exist "%~2!_count!%~3%%~x4" goto skip_count
goto _out
:_example
echo.
echo %0 USAGE EXAMPLE
echo.
echo X:\Dir\SubDir\^> dir /b
echo etc.
echo La La La.mp3
echo Le Le Le.mp3
echo Lo Lo Lo.mp3
echo Other.txt
echo.
echo X:\Dir\SubDir\^> %0 *.mp3 "" " - Su Fix"
echo.
echo X:\Dir\SubDir\^> dir /b
echo etc.
echo 1 - Su Fix.mp3
echo 2 - Su Fix.mp3
echo 3 - Su Fix.mp3
echo Other.txt
echo.
:_help
echo Rename files to increment numbers
echo.
echo CAVEAT: Works only in CURRENT directory!
echo.
echo %0 [/r] *.ext [prefix] [sufix]
echo: /? Help screen
echo /r Recurse in directories
echo *.ext Simple wildcard (like *.mp3) [NOT *.a.txt]
echo prefix Prefix to rename number
echo sufix sufix to rename number
echo.
echo When "" is used as prefix no prefix is put before the increment number
echo.
echo X:\Dir\SubDir\^> %0 [/r] [wildcard] [prefix] [sufix]
goto _out
:_out
:: REN-sec.cmd ==> End of file

Resources