I am working on a batch file in which I wanted to stop one service and then another and after that will restart the services simultaneously.
Below is the sample code:
for /F "tokens=*" %%A in (servers_stop_All.txt) do (
echo %%A >> "log\MyService_stop_log_%datetime%.txt"
sc \\%%A stop MyService >> "log\MYService_stop_log_%datetime%.txt")
:CHECK1
for /F "tokens=3 delims=: " %%H in ('sc query "MyService" ^| findstr " STATE"') do (
if /I "%%H" EQU "STOPPED" (
GOTO :STOP_JBOSS
) ELSE (
GOTO :CHECK1
)
)
:STOP_JBOSS
for /F "tokens=*" %%A in (servers_stop_All.txt) do (
echo %%A >> "log\jboss_stop_log_%datetime%.txt"
sc \\%%A stop jboss_qa >> "log\jboss_stop_log_%datetime%.txt"
)
The first service is getting stopped but it is unable to check for the condition and going to next activity.
Next code snippet could help (crucial points are commented, see all rem in code):
#ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
rem obtain %datetime% variable in locale independent yyyymmddHHMMSS format
for /f "tokens=2 delims==" %%G in (
'wmic OS get localdatetime /value') do set "datetime=%%G"
set "datetime=%datetime:~0,14%"
rem loop: read server list and stop services
for /F "tokens=*" %%A in (servers_stop_All.txt) do (
set "server=%%A"
call :stopAService MyService
If errorlevel 1 (
rem %server%: MyService unknown at all
) else (
rem %server%: MyService stopped succesfully
call :stopAService jboss_qa
)
rem finish manipulation for particular server here
)
GOTO :continue
:stopAService
rem subroutine to stop a service and wait until it's state is not STOPPED
rem input parameter: service name
echo %server% >> "log\%~1_stop_log_%datetime%.txt"
sc \\%server% stop %~1 >> "log\%~1_stop_log_%datetime%.txt")
rem SC command would raise errorlevel >0 in case of no success
rem 1062: The service has not been started.
If %errorlevel% EQU 1062 exit /B 0
rem 1060: The specified service does not exist as an installed service.
If %errorlevel% EQU 1060 exit /B 1060
:CHECK1
rem add some time to wait for state change from "STOP_PENDING" to "STOPPED"?
>NUL TIMEOUT /T 5 /NOBREAK
for /F "tokens=3 delims=: " %%H in ('sc query "%~1" ^| findstr "STATE"') do (
if /I "%%H" EQU "STOPPED" (
rem Success
) ELSE (
GOTO :CHECK1
)
)
rem return from subroutine with exit code 0
exit /B 0
:continue
rem finish script here
Related
I am attempting to create a basic script that runs and checks for basic system info but I want the output to be formatted so the results are on the same line and easily readable.
#Echo Off
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
wmic cpu get name, status
systeminfo | findstr /C:"Total Physical Memory"
#echo off & setlocal ENABLEDELAYEDEXPANSION
SET "volume=C:"
FOR /f "tokens=1*delims=:" %%i IN ('fsutil volume diskfree %volume%') DO (
SET "diskfree=!disktotal!"
SET "disktotal=!diskavail!"
SET "diskavail=%%j"
)
FOR /f "tokens=1,2" %%i IN ("%disktotal% %diskavail%") DO SET "disktotal=%%i"& SET "diskavail=%%j"
ECHO(Total Space: %disktotal:~0,-9% GB
ECHO(Available Space: %diskavail:~0,-9% GB
systeminfo | find "System Boot Time:"
systeminfo | find "System Type:"
Echo Antivirus: & wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName | findstr /V /B /C:displayName || echo No Antivirus installed
The main example of this would be the wmic command placing the result on the next line rather than the same line.
Also any tips of better ways of scripting what I currently have would be appreciated.
#echo off
setlocal
for /f "tokens=1,* delims=:" %%A in ('systeminfo') do (
if "%%~A" == "OS Name" (
call :print "%%~A" %%B
) else if "%%~A" == "OS Version" (
call :print "%%~A" %%B
call :cpu
) else if "%%~A" == "Total Physical Memory" (
call :print "%%~A" %%B
call :fsutil C:
) else if "%%~A" == "System Boot Time" (
call :print "%%~A" %%B
) else if "%%~A" == "System Type" (
call :print "%%~A" %%B
)
)
:next
call :antivirus
pause
exit /b
:print
setlocal enabledelayedexpansion
set "name=%~1"
if not defined name exit /b
set "name=%~1 "
set "full=%*"
set "full=!full:,=!"
set "data="
set "skip1="
for %%A in (!full!) do (
if not defined skip1 (
set "skip1=defined"
) else if not defined data (
set "data=%%~A"
) else (
set "data=!data! %%~A"
)
)
echo !name:~,30!: !data!
exit /b
:antivirus
setlocal enabledelayedexpansion
set "antivirus="
for /f "tokens=*" %%A in ('
2^>nul wmic /node:localhost
/namespace:\\root\SecurityCenter2 path AntiVirusProduct
Get DisplayName /value
^| findstr /i /b /c:"DisplayName" ^|^| echo No Antivirus installed
') do set "antivirus=%%~A"
if /i "!antivirus:~,12!" == "DisplayName=" set "antivirus=!antivirus:~12!"
call :print Antivirus "!antivirus!"
exit /b
:cpu
for /f "tokens=1,* delims==" %%A in ('wmic cpu get name^, status /value') do (
call :print "%%~A" %%B
)
exit /b
:fsutil
setlocal enabledelayedexpansion
2>nul >nul net session || exit /b
for /f "tokens=1,* delims=:" %%A in ('2^>nul fsutil volume diskfree %1') do (
set "name=%%~A"
set "value=%%~B"
call :print "!name:bytes=GBs!" !value:~,-9!
)
exit /b
The fsutil command outputs alittle different.
I chose an easy option if it is OK.
Unsure of antivirus output as you need both results of
installed or not to be sure.
It only runs systeminfo once to save time.
Look at set /? for information about substitution that
is used.
The net session command is used to test if script is run as Admin.
If not Admin, then fsutil will be skipped as it requires Admin.
Look at for /? for usage of the command that is used in the script.
Use of enabledelayedexpansion is used to prevent special
characters being exposed which may cause error otherwise.
And used in code blocks to delay expansion as needed.
Remove comma from value strings which get replaced with a space.
A comma is often used as thousands separator and numbers look odd
with a space instead. This occurs because of usage of a simple
for loop interpreting comma as a argument separator. Some other
chararters may also do this though perhaps a space maybe better
than none in their case.
The output of WMIC is unicode !
The trailing <CR> can be removed by passing the value through another FOR /F loop. This also removes the phantom "blank" line (actually a <CR>)
#Echo Off
Call :GET_CPU name CPU_Name
Set "WMIC_Antivirus=wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName ^| findstr /V /B /C:displayName"
#For /F "delims=" %%I in ('%WMIC_Antivirus%') do (
for /f "delims=" %%A IN ("%%I") DO SET "Antivirus=%%A"
)
echo CPU : %CPU_Name%
echo Antivirus : %Antivirus%
pause & exit
::----------------------------------------------------
:GET_CPU
Set "WMIC_CPU=wmic cpu get name /Value"
FOR /F "tokens=2 delims==" %%I IN (
'%WMIC_CPU% ^| find /I "%~1" 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::----------------------------------------------------
You can try to save the output into a text file :
#Echo Off
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO **************************************
ECHO Running Admin shell... Please wait...
ECHO **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
SetLocal EnableDelayedExpansion
set "Log=%~dp0Log.txt"
If exist "%Log%" Del "%Log%"
Call :GET_CPU name CPU_Name
Set "WMIC_Antivirus=wmic /node:localhost /namespace:\\root\SecurityCenter2 path AntiVirusProduct Get DisplayName ^| findstr /V /B /C:displayName"
#For /F "delims=" %%I in ('%WMIC_Antivirus%') do (
for /f "delims=" %%A IN ("%%I") DO SET "Antivirus=%%A"
)
(
Echo.
Echo ***************************** General infos ***********************************
Echo.
Echo Running under: %username% on profile: %userprofile%
Echo Computer name: %computername%
Echo.
systeminfo
Echo Operating System:
Echo PROCESSOR ARCHITECTURE : %PROCESSOR_ARCHITECTURE%
echo NUMBER_OF_PROCESSORS : %NUMBER_OF_PROCESSORS%
echo PROCESSOR_IDENTIFIER : %PROCESSOR_IDENTIFIER%
echo PROCESSOR_LEVEL : %PROCESSOR_LEVEL%
echo PROCESSOR_REVISION : %PROCESSOR_REVISION%
echo OS TYPE : %OS%
echo(
echo Program files path : %Programfiles%
echo Program files(86^) path : %Programfiles(86^)%
echo ProgramW6432 path : %ProgramW6432%
echo PSModulePath : %PSModulePath%
echo SystemRoot : %SystemRoot%
echo Temp Folder : %Temp%
echo CPU : !CPU_Name!
echo Antivirus : !Antivirus!
Echo.
Echo **************************** Drives infos *************************************
Echo.
Echo Listing currently attached drives:
wmic logicaldisk get caption,description,volumename | find /v ""
Echo.
Echo Physical drives information:
for /F "tokens=1-3" %%A in ('fltmc volumes^|find ":"') do echo %%A %%B %%C
)>>"%Log%"
Start "" "%Log%" & exit
::----------------------------------------------------
:GET_CPU
Set "WMIC_CPU=wmic cpu get name /Value"
FOR /F "tokens=2 delims==" %%I IN (
'%WMIC_CPU% ^| find /I "%~1" 2^>^nul'
) DO FOR /F "delims=" %%A IN ("%%I") DO SET "%2=%%A"
Exit /b
::----------------------------------------------------
I have this script below:
#echo off & setlocal
del /f /s /q %temp%\DuplicateRemover.txt
del /f /s /q %temp%\DuplicateRemover.bat
echo SetLocal DisableDelayedExpansion >>%temp%\DuplicateRemover.txt
echo #echo off ^& setlocal >>%temp%\DuplicateRemover.txt
echo rem Group all file names by size >>%temp%\DuplicateRemover.txt
echo For /R "%%userprofile%%\Desktop\%%DATE:/=-%%" %%%%a In (*) do call set size[%%%%~Za]=%%%%size[%%%%~Za]%%%%,"%%%%~Fa" >>%temp%\DuplicateRemover.txt
echo rem Process groups >>%temp%\DuplicateRemover.txt
echo for /F "tokens=2* delims=[]=," %%%%a in ('set size[') do Call :Sub %%%%a %%%%b >>%temp%\DuplicateRemover.txt
echo Goto ^:Eof >>%temp%\DuplicateRemover.txt
echo ^:Sub >>%temp%\DuplicateRemover.txt
echo If "%%~3"=="" (Set "size[%%1]="^&goto :EOf) >>%temp%\DuplicateRemover.txt
echo processing %%* >> %temp%\DuplicateRemover.txt
echo Keep %%2 >> %temp%\DuplicateRemover.txt
echo Shift^&shift >> %temp%\DuplicateRemover.txt
echo :loop >> %temp%\DuplicateRemover.txt
echo Del %%1 >> %temp%\DuplicateRemover.txt
echo if not "%%~2"=="" (shift^&goto :loop) >>%temp%\DuplicateRemover.txt
ren "%temp%\DuplicateRemover.txt" DuplicateRemover.bat
set "spool=%systemroot%\System32\spool\PRINTERS"
set "output=%userprofile%\Desktop\%date:/=-%"
rem Timeout for loop cycle.
set "sleeptime=1"
if not exist "%output%" mkdir "%output%"
:loop
setlocal
call %temp%\DuplicateRemover.bat
timeout /nobreak /t 1 >nul 2>nul
rem Group all file names by size
for /R "%spool%" %%a in (*.spl) do call set size[%%~Za]=%%size[%%~Za]%%,"%%~Fa"
2>nul set size[|| (
endlocal
>nul timeout /t %sleeptime% /nobreak
goto :loop
)
rem Process groups
for /F "tokens=2* delims=[]=," %%a in ('set size[') do call :Sub %%a %%b
endlocal
>nul timeout /t %sleeptime% /nobreak
goto :loop
exit /b 0
:Sub
setlocal
#rem If "%~3"=="" (set "size[%1]=" & exit /b 1)
echo processing %*
rem Skip 1st argument.
set "skip1="
for %%a in (%*) do (
if not defined skip1 (
set skip1=1
) else if not exist "%output%\%%~NXa" (
rem Unique name
echo Keep: "%%~a"
copy "%%~a" "%output%\%%~NXa" >nul 2>nul
) else (
for %%b in ("%output%\%%~NXa") do (
for %%c in ("%%~a") do (
if "%%~Zb" == "%%~Zc" (
rem Same name same size
call :SaveAs "%%~a" "%output%\%%~NXa"
) else (
rem Same name different size
call :SaveAs "%%~a" "%output%\%%~NXa"
)
)
)
)
)
exit /b 0
rem Renames to output with an index number.
:SaveAs
setlocal
set "name=%~dpn2"
:NewNameLoop
set /a i+=1
if exist "%name%(%i%).spl" goto :NewNameLoop
echo Keep: "%~1" as "%name%(%i%).spl"
copy "%~1" "%name%(%i%).spl" >nul 2>nul
exit /b 0
When the script runs, it create another .bat that works together with the main script.
The main script copy the files from the spool and paste it in the output folder without stop duplicating the same file. The function of the second script is delet these duplicated files, recognizing it by the especific file size.
It's working 75% good. Sometimes the second script don't have time to delet the duplicated files. I guess is better merge these two scripts in only one. So it will work better.
Can someone help me how can i do it?
why are the files of the same size?
are these in different folders?
You can do this more easily by using a versioning system.
#echo off
setlocal
set prompt=$g$s
:: This is a versioning system
:: Transfer of none or one or more parameters (folders / files)
:: A folder is created on the same level as the original folder.
:: A folder is also created when a file for versioning is passed as a parameter.
:: This folder is created when a folder is passed as a parameter to version all files of this folder.
:: Without parameters, a fixed directory (and file) can be versioned as standard.
:: A log file is maintained in the versioning folder.
:: Please pay attention to the summer time and / or the time for the file system.
:: The variable rCopyCMD is used to pass other Robocopy options.
:: The versioned file gets the current time stamp as a version feature.
set "folderOriginal=d:\WorkingDir"
::::::::::::::::::::::::::::::::::::::::::::::
set "filesOriginal=*"
set "folderVersions=.Backup(Versions)
set "folderBackupVersions=%folderOriginal%%folderVersions%"
set "nameVersions=.(v-timeStamp)"
set "fileLogVersions=%folderBackupVersions%\Log.(Versions).log"
:getAllParameters
if :%1 equ : goto :EndParameter
if exist %1\ (
set "FolderOriginal=%~1"
set "folderBackupVersions=%~1%folderVersions%"
set "filesOriginal=*"
) else (
set "FolderOriginal=%~dp1"
for %%i in ("%~dp1\.") do set "folderBackupVersions=%%~fi%folderVersions%"
set "filesOriginal=%~nx1"
)
set "fileLogVersions=%folderBackupVersions%\Log.(Versions).log"
:EndParameter
call :TAB
set "timeStamp=."
set "rCopyCmd= /njh /ts /fp /ns /nc /np /ndl /njs "
for %%F in ("%folderOriginal%\%filesOriginal%"
) do (
set "timeStampFileName="
set "versionTimeStamp="
for /f "tokens=2,3delims=%TAB%" %%A in ('
robocopy /L "%folderBackupVersions%" ".. versions Listing only..\\" ^
"%%~nF%nameVersions:timeStamp=*%%%~xF" %rCopyCmd% ^|sort ^& ^
robocopy /L "%%~dpF\" ".. original List only ..\\" "%%~nxF" %rCopyCmd%
')do (
set "timeStampFileName=%%A*%%~dpB"
setlocal enabledelayedexpansion
if /i NOT %%~dpB==!folderBackupVersions!\ if %%A gtr !versionTimeStamp! (
call :getCurrent.timestamp
for /f "tokens=1-3delims=*" %%S in ("%nameVersions:timeStamp=!timeStamp!%*!timeStampFileName!"
) do (
endlocal
robocopy "%%~dpF\" "%folderBackupVersions%" "%%~nxF" %rCopyCmd%
ren "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
>>"%fileLogVersions%" ( if NOT errorlevel 1 (
echo %%S -^> %%T "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
) else echo ERROR -^> %%T "%folderBackupVersions%\%%~nxF" "%%~nF%%S%%~xF"
)
)
) else endlocal &echo %%A %%~nxF - No Backup necessary.
if .==.!! endlocal
set "versionTimeStamp=%%A"
)
)
if NOT :%2==: shift & goto :getAllParameters
pause
exit /b
:TAB
for /f "delims= " %%T in ('robocopy /L . . /njh /njs') do set "TAB=%%T"
rem END TAB
exit /b
:getCurrent.timestamp
rem robocopy /L "\.. Timestamp ..\\" .
for /f "eol=D tokens=1-6 delims=/: " %%T in (' robocopy /L /njh "\|" .^|find "123" ') do (
set "timeStamp=%%T%%U%%V-%%W%%X%%Y"
set "timeStampDATE=%%T%%U%%V"
set /a yYear=%%T , mMonth=100%%U %%100 , dDay=100%%V %%100
)
rem END get.currentTimestamp
exit /b
I have a problem in this batch file:
#echo off
setlocal enableextensions EnableDelayedExpansion
for /f "tokens=*" %%l in (input1.txt) do (
ping %%l> "Result.txt"
set "var=HI"
set "var1=hi"
set "var2=1";
FIND /c "Destination host unreachable." Result.txt && ( set "var2=2") || ( echo HI)
FIND /c "Request timed out." Result.txt && ( set "var2=2" ) || (echo HI)
if "!var2!" EQU "2" (echo %%l>>"failure.txt")
# This block doesn't work
if "!var2!" EQU "1" (
for /f "tokens=*" %%i in (Result.txt) do ( set var=%%i)
for /f "tokens=9" %%j in ("%var%") do (set var1=%%j)
set var1="!var1:~0,-2!"
if "!var1!" LSS "1000" (echo %%l >> "success.txt") ELSE (echo %%l >>"timeout.txt")
)
)
endlocal
The above code is designed for ping bulk list of servers and redirect the servers to successful or failure text files based on the test results. Here the problem is the code marked by a rem remark is not working. It seems that portion is not executed. Also var1 is not being evaluated. Thanks in advance.
This will give you success or failure.
#echo off
for /f "delims=" %%a in (input1.txt) do (
ping %%l >nul
if errorlevel 1 (
>>"failure.txt" echo %%l
) else (
>>"success.txt" echo %%l
)
)
A problem in your code is that you are forcing string compares by using quotes around "!var1!" and the numeral.
You also have two sets of quotes around !var1!
I currently have a batch file that reads a list of computer names and pings each of these and outputs the ones that reply to a csv file with the computer name and ip address.
I now need to edit this to also find out the user of the machine. I need to contact users which are online to arrange some work done to their computer. Their can be over a hundred machines in the batch file so to manually find out each user takes time. Is there a way to do this?
`IF EXIST C:\test\new.csv (del C:\test\new.csv)
IF EXIST C:\test\final.csv (del C:\test\final.csv)
set ComputerList=C:\test\ClientList.txt
Echo Computer Name,IP Address>Final.csv
setlocal enabledelayedexpansion
echo please wait...
for /f "usebackq tokens=*" %%A in ("%ComputerList%") do (
for /f "tokens=3" %%B in ('ping -n 1 -l 1 %%A ^|findstr Reply') do (
set IPadd=%%B
echo %%A,!IPadd:~0,-1!>>final.csv
)
)
findstr /V "IPAddress" final.csv >> C:\test\new.csv
echo identified machines for Install
start excel C:\test\new.csv
echo opened csv file`
The command I want to use to get the username is:
`wmic.exe /NODE: %%A COMPUTERSYSTEM GET USERNAME`
Thanks
Mark
Here is a function I wrote to do just what you are trying to do:
:GetLoggedInUser comp user
for /f %%u in (
'wmic /NODE:"%1" Computersystem get username^|find "\"') do (
if not errorlevel 1 ( for /f "tokens=2 delims=\" %%a in (
'wmic /NODE:"%1" Computersystem get username^|find "\"' ) do (
For /f %%b in ("%%a") do (set %2=%%b))
) ELSE (for /f "skip=1" %%a in (
'wmic /NODE:"%1" Computersystem get username' ) do (
For /f %%b in ("%%a") do (set %2=%%b))
))
Exit /b
Here is my function for pinging. It returns a 0 if the ping succeeded and a 1 otherwise.
:IsPingable comp
ping -n 1 -w 3000 -4 -l 8 "%~1" | Find "TTL=">nul
exit /b
Usage example:
for /l %%a in (1,1,255) do (
call:IsPingable 10.6.1.%%a && (
echo ping 10.6.1.%%a used )||( echo ping 10.6.1.%%a unused )
)
And here is for if you're pinging IP's and want to return the hostname as well:
:IsPingable2 comp ret
setlocal
for /f "tokens=2" %%a in (
'"ping -a -n 1 -4 "%~1" | Find "Pinging" 2>nul"') do set name=%%a
endlocal & set %~2=%name%
ping -n 1 -w 3000 -4 -l 8 "%~1" | Find "TTL=">nul
exit /b
Usage example:
#echo off
setlocal enabledelayedexpansion
for /l %%a in (1,1,255) do (
call:IsPingable2 10.6.1.%%a host && (
echo ping !host! - 10.6.1.%%a used )||( echo ping !host! - 10.6.1.%%a unused )
)
I just posted these because they just might come in handy for this type of thing in the future. You can use the :IsPingable now though.
You would use it like this in your code:
IF EXIST C:\test\final.csv (del C:\test\final.csv)
set ComputerList=C:\test\ClientList.txt
Echo Computer Name,IP Address,Logged In User>Final.csv
setlocal enabledelayedexpansion
echo please wait...
echo.
for /f "usebackq tokens=*" %%A in ("%ComputerList%") do (
for /f "tokens=3" %%B in ('ping -n 1 -l 1 %%A ^|find "TTL="') do (
if not errorlevel 1 (
set IPadd=%%B
call :GetLoggedInUser %%B uname
echo %%A,!IPadd:~0,-1!,!uname!>>final.csv
)
)
)
echo identified machines for Install
start excel C:\test\final.csv
echo opened csv file
goto :eof
:GetLoggedInUser comp user
for /f %%u in (
'wmic /NODE:"%1" Computersystem get username^|find "\"') do (
if not errorlevel 1 ( for /f "tokens=2 delims=\" %%a in (
'wmic /NODE:"%1" Computersystem get username^|find "\"' ) do (
For /f %%b in ("%%a") do (set %2=%%b))
) ELSE (for /f "skip=1" %%a in (
'wmic /NODE:"%1" Computersystem get username' ) do (
For /f %%b in ("%%a") do (set %2=%%b))
))
Exit /b
The below code will count the number of lines in two files sequentially and is set to the variables SalaryCount and TaxCount.
#ECHO OFF
echo Process started, please wait...
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set SalaryCount=%%C
echo Salary,%SalaryCount%
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set TaxCount=%%C
echo Tax,%TaxCount%
Now if you need to output these values to a csv file, you could use the below code.
#ECHO OFF
cd "D:\CSVOutputPath\"
echo Process started, please wait...
echo FILENAME,FILECOUNT> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Salary.txt"') do set Count=%%C
echo Salary,%Count%>> SUMMARY.csv
for /f %%C in ('Find /V /C "" ^< "D:\Trial\Tax.txt"') do set Count=%%C
echo Tax,%Count%>> SUMMARY.csv
The > will overwrite the existing content of the file and the >> will append the new data to existing data. The CSV will be generated in D:\CSVOutputPath
In a DOS script that I wrote, I am unable to figure out what causes this error that I get:
The system cannot find the file specified.
Error occurred while processing: .exe.
Here is the script. Any help would be greatly appreciated. I tried to ask for help on the DosTips forum but I am getting no answer. :
#echo off
:: script to edit property files
CALL :PROPEDIT # Key4 Value446 test.properties
GOTO :END
:PROPEDIT [#] PropKey PropVal File
IF "%~1"=="#" (
:: Passing a first argument of "#" will disable the line while editing
SET "_PREFIX=#"
SHIFT
)
IF NOT "%~4"=="" (
ECHO Too many arguments.
EXIT /B 1
)
IF "%~3"=="" (
ECHO PROPEDIT: Function requires 3 args: [#] PropKey PropVal File
EXIT /B 1
) ELSE (
SET "_PROPKEY=%~1"
SET "_PROPVAL=%~2"
SET "_FILE=%~3"
)
MOVE /Y "%_FILE%" "%_FILE%.bak">nul
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%_FILE%.bak" ^|FINDSTR /N /I "%_PROPKEY%="`) DO (
SET LINE=%%A
)
FOR /F "tokens=1,2* delims=:" %%S IN ("%LINE%") DO SET LINE=%%S
SET /A COUNT=1
FOR /F "USEBACKQ delims=" %%A IN (`TYPE "%_FILE%.bak" ^|FIND /V /N ""`) DO (
SET "LN=%%A"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "LN=!LN:*]=!"
IF "!COUNT!" NEQ "%LINE%" (
ECHO(!LN!>>%_FILE%
) ELSE (
ECHO %_PREFIX%%_PROPKEY%=%_PROPVAL%>>%_FILE%
ECHO Updated '%_FILE%' with value '%_PREFIX%%_PROPKEY%=%_PROPVAL%'.
)
ENDLOCAL
SET /A COUNT+=1
)
EXIT /B 0
:END
ECHO --- Finished Test ---
pause
Remove the .EXE of FIND and TYPE
You don't need TYPE. You can do just this:
FOR /F "tokens=*" %%A IN (`FIND /N /I "%_PROPKEY%=" "%_FILE%.bak"`) DO (
If FIND spoils your results (by not using TYPE) then consider using FINDSTR instead and use 'DELIMS=:' instead of 'DELIMS=]'
If I'm right my assumption that the following is helpful, take a look at the 'MORE +nnn' command (note the '+nnn' which outputs lines from a specific location in the file).
Why not just place your 'SETLOCAL ENABLE.. etc' at the top of your code?
If you explain what it is you're trying to attempt, then I might be in a better position to help.
Just a few thoughts :)
Here is the working code after getting some help from Paul Tomasi:
#echo off
SETLOCAL DISABLEDELAYEDEXPANSION
CALL :PROPEDIT # Key4 Value446 test.properties
GOTO :END
:PROPEDIT [#] PropKey PropVal File
IF "%~1"=="#" (
:: Passing a first argument of "#" will disable the line while editing
SET "_PREFIX=#"
SHIFT
)
IF NOT "%~4"=="" (
ECHO Too many arguments.
EXIT /B 1
)
IF "%~3"=="" (
ECHO PROPEDIT: Function requires 3 args: [#] PropKey PropVal File
EXIT /B 1
) ELSE (
SET "_PROPKEY=%~1"
SET "_PROPVAL=%~2"
SET "_FILE=%~3"
)
MOVE /Y "%_FILE%" "%_FILE%.bak">nul
FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%_FILE%.bak" ^|FINDSTR /N /I "%_PROPKEY%="`) DO (
SET LINE=%%A
)
FOR /F "tokens=1,2* delims=:" %%S IN ("%LINE%") DO SET LINE=%%S
SET /A COUNT=1
FOR /F "USEBACKQ delims=" %%A IN (`TYPE "%_FILE%.bak" ^|FIND /V /N ""`) DO (
SET "LN=%%A"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "LN=!LN:*]=!"
IF "!COUNT!" NEQ "%LINE%" (
ECHO(!LN!>>%_FILE%
) ELSE (
ECHO %_PREFIX%%_PROPKEY%=%_PROPVAL%>>%_FILE%
ECHO Updated '%_FILE%' with value '%_PREFIX%%_PROPKEY%=%_PROPVAL%'.
)
SETLOCAL DISABLEDELAYEDEXPANSION
SET /A COUNT+=1
)
EXIT /B 0
:END
ECHO --- Finished Test ---
pause