Hello I have a problem with a script, I would like the following from this script. First of all I want to create a folder with the month specific to my computer and in that folder to events logs,but save only application event and system event without the security even if the script is run with admin rights nothing happens. Bellow is my script
#echo off
rem Script starts here
rem Timestamp Generator
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set "dt=%%a"
:: Format the WMIC command output in YY_MM_DD_hr_mn format
set "YY=%dt:~0,4%"
set "MM=%dt:~4,2%"
set "DD=%dt:~6,2%"
set "hr=%dt:~8,2%"
set "mn=%dt:~10,2%"
:: Format the MM (month-number) to display the month-name
if %MM%==01 set MM=Ianuarie
if %MM%==02 set MM=Februarie
if %MM%==03 set MM=Martie
if %MM%==04 set MM=Aprilie
if %MM%==05 set MM=Mai
if %MM%==06 set MM=Iunie
if %MM%==07 set MM=Iulie
if %MM%==08 set MM=August
if %MM%==09 set MM=Septembrie
if %MM%==10 set MM=Octombrie
if %MM%==11 set MM=Noiembrie
if %MM%==12 set MM=Decembrie
set "today_date_time=%MM%_%YY%"
echo %today_date_time%
mkdir .\%today_date_time%
rem Set the timestamp format
wevtutil epl System %MM%_%YY%\system.evtx
wevtutil epl Application %MM%_%YY%\application.evtx
wevtutil epl Security %MM%_%YY%\security.evtx
wmic nteventlog where filename='system' cleareventlog
wmic nteventlog where filename='application' cleareventlog
wmic nteventlog where filename='security' cleareventlog
rem End of Script
Here's a re-written example without all of the WMIC.exe stuff, as per your commented request:
#Rem Start of script.
#Echo Off
SetLocal EnableExtensions
Rem End script if end user is not running with the required permissions.
%SystemRoot%\System32\reg.exe Query "HKU\S-1-5-19" 1>NUL 2>&1 || GoTo :EOF
Rem Add the current directory to the stack and make this scripts location the current directory.
PushD "%~dp0."
Rem Generate a datestamp variable with a string formatted as yy_MMMM.
Set "DateStamp="
For /F %%G In ('%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile "Get-Date -F 'yy_MMMM'" 2^>NUL') Do Set "DateStamp=%%G"
Rem End script if datestamp variable was not defined.
If Not Defined DateStamp GoTo :EOF
Rem Backup and clear event logs.
If Not Exist "%DateStamp%\" MD "%DateStamp%"
For %%G In (Application Security System) Do %SystemRoot%\System32\wevtutil.exe cl %%G /bu:"%DateStamp%\%%G.evtx"
Rem Make the previous directory in the stack the current directory.
PopD
Rem End of Script.
The script was designed to just close, if the end user did not Run as administrator. Also the backup files will be saved to the same location as the running batch file.
Related
I am new at batch scripting and looking for a way to extract the "Product Version" field of an .exe file using a command on cmd.
I did managed to get the regular "Version" field of a file using this command:
wmic datafile where Name="C:\\Users\\MyProgram.exe" get Version
is there any way to modify this command line for extracting the "Product Version" field?
Any other solution without wmic at all will also be good :)
thanks.
You can give a try with this batch file to get easily your Product Version; in this example i tried with Google chrome :
#echo off
Title Get Product Version Using WMIC and Batch
Set FullPath=C:\Program Files\Google\Chrome\Application\chrome.exe
Call :Get_AppName "%FullPath%" AppName
Call :GetVersion "%FullPath%" Version
If defined Version (
echo "%FullPath%" ==^> v%Version%
echo "%AppName%" ==^> %Version%
)
Pause
EXIT /B
::----------------------------------------------------------------------------------------
:GetVersion <FullPathApp> <Version>
Rem The argument %~1 represent the full path of the application without the double quotes
Rem The argument %2 represent the variable to be set (in our case %2=Version)
Set "FullPathApp=%~1"
Set "FullPathApp=%FullPathApp:\=\\%"
FOR /F "tokens=2 delims==" %%I IN (
'wmic datafile where "name='%FullPathApp%'" get version /Value 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::----------------------------------------------------------------------------------------
:Get_AppName <FullPath> <AppName>
Rem %1 = FullPath
Rem %2 = AppName
for %%i in (%1) do set "%2=%%~nxi"
exit /b
::---------------------------------------------------------------------------------------
Or You can try with Powershell and Batch inspired from Get File Version in PowerShell :
#echo off
Title Get Product Version using Powershell and Batch
Set FullPath=C:\Program Files\Google\Chrome\Application\chrome.exe
echo %FullPath%
Powershell -C "(Get-Item '%FullPath%').VersionInfo.FileVersion"
Pause
(TLDR see last paragraph)
Below code I have cobbled together with information from other threads in this forum and others. I am very new to this code/language so I don't have a clue how to optimize this.
Here is what I am trying to achieve with this code.
script outputs to a .log instead of command window
:top
script searches for a .dat file in "M:\AnalysisDrop\"
if a .dat file is detected (
script automatically creates a subfolder "M:\AnalysisDrop\title_date_time"
file is moved into the folder
file is opened with the program C:\Analysis\Analysis.exe
)
wait 5 seconds
goto top (repeat forever)
this script will continuously repeat for what I hope to be a very long time. Will I run into issues with too many "set" commands? I ran into some issue with doing "SETLOCAL EnableDelayedExpansion" and SETLOCAL DisableDelayedExpansion
#Echo off
echo Script 1 Initiated
#echo on
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime1=%datetime:~0,8%_%datetime:~8,6%
SETLOCAL EnableDelayedExpansion
SET LOGFILE=Script1_LOG_%datetime1%.log
call :top >> %LOGFILE%
exit /b 0
:top
for %%f in (*.dat) do (
set datetime1=%datetime:~0,8%_%datetime:~8,6%
set foldername=%%~nf_%datetime1%
md "!foldername!"
move "M:\AnalysisDrop\%%~nf*.dat*" "M:\AnalysisDrop\%%~nf_%datetime1%\"
pushd M:\AnalysisDrop\%%~nf_%datetime1%\
C:\Analysis\Analysis.exe '%%~nf.dat'
popd
)
timeout /t 5 /nobreak
goto top
exit /b 0
I honestly dont need the "for" loop but i'm not sure how to do otherwise (tried to replace "for" with "if", no success. Also, the "datetime1" variable wont update, so if I try to run multiple .dat files of the same name, it writes over the previous one in the same subfolder, which I can live with but prefer not to have.
So to clarify my questions:
1. How do i do this without the "for" loop? I understand this may be causing my issue of the datetime variable not updating.
2. I used the "goto" command to continuously loop this script, should I use something different?
Answer to my question, with help from #compo. I wasn't aware that I needed the for \f... statement in the loop as well as the set datetime2. I needed to change %datetime...% to !datetime...! throughout the for loop. See below for fixed code.
In response to #Gerhard Barnard, %time% and %date% is not in a format that I can name directories with unfortunately.
#Echo off
echo Script 2 Initiated
#echo on
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime2=%datetime:~0,8%_%datetime:~8,6%
SETLOCAL EnableDelayedExpansion
SET LOGFILE=Script2_LOG_%datetime2%.log
call :top >> %LOGFILE%
:top
for %%f in (*.dat) do (
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
set datetime2=!datetime:~0,8!_!datetime:~8,6!
set foldername=%%~nf_!datetime2!
md "!foldername!"
move "M:\AnalysisDrop\%%~nf*.dat*" "M:\AnalysisDrop\!foldername!\"
pushd M:\AnalysisDrop\!foldername!\
C:\Analysis\Analysis.exe '%%~nf.dat'
popd
)
timeout /t 5 /nobreak
goto top
exit /b 0
I hope this, based upon your original code, helps you with structuring your script:
#Echo Off
Rem Enabling delayed expansion
SetLocal EnableDelayedExpansion
Rem Setting current directory
If /I Not "%CD%"=="M:\AnalysisDrop" (CD /D "M:\AnalysisDrop" 2>Nul||Exit/B)
Rem Setting date and time variable for log file name
Call :GetLDT
Rem Call Main section outputting to log file
Call :Main>>"Script1_LOG_%LDT%.log"
Rem Exit script
Exit/B
Rem Main section
:Main
Rem Loop over each matching file in the current directory
For %%A In (*.dat) Do (
Rem Setting date and time variable for destination directory name
Call :GetLDT
Rem Create directory if it does not exist
If Not Exist "%%~nA_!LDT!\" MD "%%~nA_!LDT!"
Rem Move file to directory
Move "%%~A" "%%~nA_!LDT!"
Rem Run analysis against file in destination
Start "" /D "%%~nA_!LDT!" /W "C:\Analysis\Analysis.exe" '%%~A'
)
Rem Create a delay
Timeout 5 /NoBreak>Nul
Rem Re-run Main section in loop
GoTo Main
Rem GetLDT section
:GetLDT
Rem Setting date and time string
For /F "EOL=L" %%A In ('WMIC OS GET LocalDateTime') Do For %%B In (%%~nA
) Do Set "LDT=%%B"
Rem Formatting string as required
Set "LDT=%LDT:~,8%_%LDT:~-6%"
Rem Return to point after Call
GoTo :EOF
Your command using '%%~A' looks wrong with single quotes, but I'll leave that to you to decide.
I have a log file (job.log) that contains a jobID that is always changing.
How do I open this file and parse the job ID and store 761 to a variable so I can use it for other command references? Again, this log will always have a different jobID so I'm looking for a dynamic way to do this.
"RUNNING","jobId":761,"logFileName":"outbox/logs/AQCONSOL-Finance_761.log
FYI, within my bat file, I will use the following command to download this log file...
call automate downloadfile "outbox/logs/AQCONSOL-Finance_"%jobid%".log"
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\Q43128657.txt"
FOR /f "usebackq tokens=3 delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named Q43128657.txt containing your data for my testing.
Simply parse the line using : and , as delimiters and select the third token.
Revision to select file "rundatarule*.log"
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN ('dir /b /a-d /od "%sourcedir%\rundatarule*.log" ') DO SET "filename1=%sourcedir%\%%a"
FOR /f "usebackqtokens=3delims=:," %%a IN ("%filename1%") DO SET job=%%a
ECHO job is %job%
GOTO :EOF
The dir command lists matching files in /b basic form /a-d with no directorynames /od in order of date (just in case there are multiple files, select the very last chronologically) and processes that list, applying the entire name (in case there are separators) to %%a and thus assigning the reconstructed name (with the directory) to filename1.
It is considered good practice to format date-timestamps as ymdhms, not dmyhms as this provides an easily-sortable sequence.
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 /?
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.