parsing string in a log file in VBS - windows

I have a windows system logs information to a text file. It is a bat file and records current date, time and result of a cygwin command to a text file.
Current text file is below.
Fri 05/16/2014 16:52:12.19
JAVA_HOME = C:/jdk1.6.0_07
Checking rmi://ppm01:1094/KintanaServer
--> running (load: 343.0, mode: NORMAL)
Checking rmi://ppm02:1197/KintanaServer
--> running (load: 318.0, mode: NORMAL)
Checking rmi://ppm03:1297/KintanaServer
--> running (load: 0.0, mode: NORMAL)
-------------------------------------------
Fri 05/16/2014 16:57:00.03
JAVA_HOME = C:/jdk1.6.0_07
Checking rmi://ppm01:1094/KintanaServer
--> running (load: 334.0, mode: NORMAL)
Checking rmi://ppm02:1197/KintanaServer
--> running (load: 334.0, mode: NORMAL)
Checking rmi://ppm03:1297/KintanaServer
--> running (load: 0.0, mode: NORMAL)
I want to change the text file to
Fri 05/16/2014 16:52:12.19;ppm01;343
Fri 05/16/2014 16:52:12.19;ppm01;318
Fri 05/16/2014 16:52:12.19;ppm03;0
Fri 05/16/2014 16:57:00.03;ppm01;334
Fri 05/16/2014 16:57:00.03;ppm02;334
Fri 05/16/2014 16:57:00.03;ppm02;0
How can I manipulate current text file with VBS to grap the information.
I could not change the command in cygwin also the result of the cygwin command. So what I only could do is changing the already written information.
Here my batch script:
#echo off
C:
cd C:\ppm\bin
echo %date% %time% >> userload_log.txt
C:\cygwin\bin\bash.exe kStatus.sh >> userload_log.txt

For the file format change (batch file, not vbscript)
#echo off
setlocal enableextensions enabledelayedexpansion
set /a "mon=100", "tue=100", "wed=100", "thu=100", "fri=100", "sat=100", "sun=100"
set /a "checking=200", "running=300"
for /f "usebackq tokens=1-8 delims=>-/:. " %%a in ("userload_log.txt") do (
set /a "id=%%a"
if !id! equ 100 (
set "ts=%%a %%b/%%c/%%d %%e:%%f:%%g.%%h;"
) else if !id! equ 200 (
set "ppm=%%c;"
) else if !id! equ 300 (
echo(!ts!!ppm!%%c
)
)
This code tokenizes the lines and uses the first token to determine the information that can be retrieved from it. The rest is saving the adecuated tokens in variables and each time a complete set is retrieved, echo to console the required record
For a VBS version
Option Explicit
Const ForReading = 1
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Dim inputFile
Set inputFile = fso.OpenTextFile("userload_log.txt", ForReading )
Dim reDate, reChecking, reRunning
Dim inputLine, id, ts, ppm
Do While Not inputFile.AtEndOfStream
inputLine = Trim(inputFile.ReadLine())
If Len(inputLine) > 0 Then
id = split(LCase(inputLine)," ")(0)
Select Case id
Case "mon","tue","wed","thu","fri","sat","sun"
ts = inputLine
Case "checking"
ppm = Split(Mid(inputLine,16),":")(0)
Case "-->"
WScript.StdOut.WriteLine ts & ";" & ppm & ";" & Split(Mid(inputLine,20),".")(0)
End Select
End If
Loop
inputFile.Close()

Related

Run a bat file on specific date

I want to know how I can run a .bat file on a specific date.
Sample code:
if "%date%" == " Wed 08/04/2021"
start "" "C:\Users\CIM\Downloads\deletefile.bat"
if %DATE:~10,4%%DATE:~4,2%%DATE:~7,2% EQU "20210408" (
start "" "C:\Users\CIM\Downloads\deletefile.bat"
)

Auto Import Script not Working

I'm an absolute beginner with VB hence I might ask some silly questions.
I have a VB script getting triggered via a Batch file which results in data being imported for last day.
Below is the code for VB and Batch file.
Please let me know if you see any error in the code.
VB Script
rem
rem XLink_Import.vbs
rem
Set oShell = WScript.CreateObject("WScript.Shell")
' filename = oShell.ExpandEnvironmentStrings("today_xlink.bat")
' Set objFileSystem = CreateObject("Scripting.fileSystemObject")
' Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
Dim i
Dim ImportStartOffset, ImportedNumberOfDays
If WScript.Arguments.length > 0 Then
For i=0 to WScript.Arguments.length-1
Arg = WScript.Arguments(i)
If Left(Arg,1) = "-" Then
If ( Arg = "-o" ) Then
ImportStartOffset = WScript.Arguments(i+1)
End if
If ( Arg = "-n" or Arg = "-l" ) Then
ImportedNumberOfDays = WScript.Arguments(i+1)
End if
End if
Next
End If
rem Prepare the import start date
Dim Dy, Mth
Dim ImportDate
ImportDate = Now + ImportStartOffset
Dy = Day(ImportDate)
Mth = Month(ImportDate)
If Len(Dy) = 1 Then Dy = "0" & Dy
If Len(Mth) = 1 Then Mth = "0" & Mth
ImportStartDate = Dy & "/" & Mth & "/" & Year(ImportDate)
rem Prepare import script to run (not useed yet)
rem oFile.WriteLine("isps_ul.exe -t -d " & todaydate & " -L 1")
rem oFile.Close
rem Run XLink import
wscript.echo "isps_ul.exe -t -d " & ImportStartDate & " -L " & ImportedNumberOfDays
oShell.Run "isps_ul.exe -t -d " & ImportStartDate & " -L " & ImportedNumberOfDays, 1, true
Batch File
#echo off
rem
rem XLink_Import.bat
rem
rem Manually starts an Xlink import starting today + a StartOffset of some days.
rem Imported number of days can also be set.
rem
set ImportStartOffset=0
set ImportedNumberOfDays=1
cscript XLink_Import.vbs -o %ImportStartOffset% -n %ImportedNumberOfDays%
pause
You don't need both a batch and a script, one of either would be enough, doing the whole thing in batch would require with some suggling with special parameters and I'm not into that so I'll adapt your script a bit like below.
Since you keep your 2 confiuration variables in the windows environment you can read them from vbscript as well, other option would be to read from a configuration file, from the command line like you did or keep the in the script itself.
Your middle part, makig sure the date is speleld correct could be omitted if you set those dates correctly in the configuration (environmentvariables).
If your import is going to work you should check before by running what is displayed as command, so eg "eisps_ul.exe -t -d28/11/2016 -L" should run, otherwise search on that problem first.
What I meant in my comment about being DRY means you should not repeat things, in case of your command you can store the concatenated command in a variable and use that for viewing and running.
Dim ImportStartOffset, ImportedNumberOfDays, oShell, command, Dy, Mth, ImportDate, ImportStartDate
Constant WaitOnReturn = true, WindowStyle = 1 '1 = Activate and display
'read configuration environment variables
Set oShell = CreateObject( "WScript.Shell" )
ImportStartOffset = wshShell.ExpandEnvironmentStrings( "%ImportStartOffset%" )
ImportedNumberOfDays = wshShell.ExpandEnvironmentStrings( "%ImportedNumberOfDays%" )
'Prepare the import start date (not necessary if environmentvariables would be configured well)
ImportDate = Now + ImportStartOffset
Dy = Day(ImportDate)
Mth = Month(ImportDate)
If Len(Dy) = 1 Then Dy = "0" & Dy
If Len(Mth) = 1 Then Mth = "0" & Mth
ImportStartDate = Dy & "/" & Mth & "/" & Year(ImportDate)
'Run XLink import
command = "isps_ul.exe -t -d " & ImportStartDate & " -L " & ImportedNumberOfDays
wscript.echo command
oShell.Run command, WindowStyle, WaitOnReturn
Set oShell = Nothing

windows batch file change blank field to value

I am writing a windows script to read in a txt file with 9 columns of data
I want to write this data out to a csv file to be loaded into a database.
I have found that one column is sometimes blank, so I would like to enter code 'rdp'
another column has mostly numbers, but for reason some values are a '.' (presumably indicating value less than 1. I would like to change these values to '0'
my code
for /F %%b in (c:\ts_users\newfiles_list.txt) do (
for /F "tokens=1,2,3,4,5,6,7,8,9" %%i in (%%b) do (
echo %%i,%%j,%%k,%%l,%%m,!idle!,%%o %%p,%%q >>%%~nb.csv
)
)
this manages to read in the txt file, then write it out as a csv.
column k is sometimes empty, column n sometimes has a '.'
I have tried variations of
set var=rdp
if %%k="" then set !k:=!var!
which doesnt work, so I a little stumped (after googling internet for days)
current input
201401241611 USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME eu1ptsw002
201401241611 julie.noble rdp-tcp#9 3 Active 18 24/01/2014 14:24 eu1ptsw002
201401241611 svc.perfmon18 7 Disc 3 24/01/2014 14:15 eu1ptsw002
201401241611 reto.hofstetter 10 Disc 40 24/01/2014 10:57 eu1ptsw002
201401241611 lester.valentin 14 Disc 1:16 24/01/2014 11:53 eu1ptsw002
201401241611 philippe.bachmann 15 Disc 2 24/01/2014 12:45 eu1ptsw002
201401241611 patrik.soderlund rdp-tcp#2 21 Active 24 24/01/2014 07:42 eu1ptsw002
current output
201401241611,USERNAME,SESSIONNAME,ID,STATE,,TIME LOGON,TIME
201401241611,julie.noble,rdp-tcp#9,3,Active,,24/01/2014 14:24,eu1ptsw002
201401241611,svc.perfmon18,7,Disc,3,,14:15 eu1ptsw002,
201401241611,reto.hofstetter,10,Disc,40,,10:57 eu1ptsw002,
201401241611,lester.valentin,14,Disc,1:16,,11:53 eu1ptsw002,
201401241611,philippe.bachmann,15,Disc,2,,12:45 eu1ptsw002,
201401241611,patrik.soderlund,rdp-tcp#2,21,Active,,24/01/2014 07:42,eu1ptsw002
required output
201401241611,USERNAME,SESSIONNAME,ID,STATE,,TIME LOGON,TIME
201401241611,julie.noble,rdp-tcp#9,3,Active,18,24/01/2014 14:24,eu1ptsw002
201401241611,svc.perfmon18,rdp,7,Disc,3,24/01/2014 14:15,eu1ptsw002
201401241611,reto.hofstetter,rdp,10,Disc,40,24/01/2014 10:57,eu1ptsw002,
201401241611,lester.valentin,rdp,14,Disc,1:16,24/01/2014 11:53,eu1ptsw002
201401241611,philippe.bachmann,rdp,15,Disc,2,24/01/2014 12:45,eu1ptsw002
201401241611,patrik.soderlund,rdp-tcp#2,21,Active,24,24/01/2014 07:42,eu1ptsw002
#echo off &setlocal disableDelayedExpansion
for /f "delims=" %%a in (file) do (
set "line=%%~a"
setlocal enabledelayedexpansion
set "line=!line:,.,=,0,!"
set "line=!line:,,=,rdp,!"
echo(!line!
endlocal
)

VBS or Bat - Determine OS and Office Version

Does anyone have a script that can determine the Windows OS and Office Version in the same script.
I have bits and pieces of the script but I can't seem to figure out how to incorporate both OS and Office Version in the script. I started out in bat now I moved on to VBS as it seems to be able to provide more details however, if someone could just help out with logic in below I might be able to move forward.
I would like to know how I can setup a script like this.
If Windows 7 64bit & Office 2010
do this
If Windows XP 32bit & Office 2007
do this
If Windows 7 & Office 2007
do this
CODE FOR Detecting Windows Version -- BAT SCRIPT
Echo Please wait.... detecting Windows OS version...
ver | find "2003" > nul
if %ERRORLEVEL% == 0 goto done
ver | find "XP" > nul
if %ERRORLEVEL% == 0 goto ver_xp
ver | find "2000" > nul
if %ERRORLEVEL% == 0 goto done
ver | find "NT" > nul
if %ERRORLEVEL% == 0 goto done
if not exist %SystemRoot%\system32\systeminfo.exe goto warnthenexit
systeminfo | find "OS Name" > %TEMP%\osname.txt
FOR /F "usebackq delims=: tokens=2" %%i IN (%TEMP%\osname.txt) DO set vers=%%i
echo %vers% | find "Windows 7" > nul
if %ERRORLEVEL% == 0 goto ver_7
echo %vers% | find "Windows Server 2008" > nul
if %ERRORLEVEL% == 0 goto done
echo %vers% | find "Windows Vista" > nul
if %ERRORLEVEL% == 0 goto ver_7
goto warnthenexit
Although the the Office part is kind of slow, it does work.
Just include this inside a file with a name like getversions.vbs
On my computer, it printed:
Microsoft Windows 8 Enterprise
Microsoft Office 32-bit Components 2013, Version15
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
Wscript.Echo objOperatingSystem.Caption
Next
Set colSoft = objWMIService.ExecQuery("SELECT * FROM Win32_Product WHERE Name Like 'Microsoft Office%'")
If colSoft.Count = 0 Then
wscript.echo "NO OFFFICE INSTALLED"
else
For Each objItem In colSoft
Wscript.echo objitem.caption & ", Version" & Left(objItem.Version, InStr(1,objItem.Version,".")-1)
exit for
Next
End If
Save this (VB Script) file as GetVersions.vbs.
It works
Regards,
Shaun
Option Explicit ' Enforce variable declaration
' Declare objects
Dim oShell
Dim sOSVersion
Dim lOfficeVersion
Set oShell = CreateObject("WScript.Shell")
On Error Resume Next
sOSVersion = oShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName")' Read the registry for the operating system version
lOfficeVersion = GetOfficeVersionNumber() ' Read the office version from the function
MsgBox "sOSVersion = " & sOSVersion & vbCrLf & "lOfficeVersion = " & lOfficeVersion
Function GetOfficeVersionNumber()
GetOfficeVersionNumber = "" ' or you could use "Office not installed"
Dim sTempValue
' Read the Classes Root registry hive (it is a memory-only instance amalgamation of HKCU\Software\Classes and HKLM\Software\Classes registry keys) as it contains a source of information for the currently active Microsoft Office Excel application major version - it's quicker and easier to read the registry than the file version information after a location lookup). The trailing backslash on the line denotes that the # or default registry key value is being queried.
sTempValue = oShell.RegRead("HKCR\Excel.Application\CurVer\")
If Len(sTempValue) > 2 Then GetOfficeVersionNumber = Replace(Right(sTempValue, 2), ".", "") ' Check the length of the value found and if greater than 2 digits then read the last two digits for the major Office version value
End Function ' GetOfficeVersionNumber

Trouble compressing large files using vbs

I have jumbled up a vbs script to compress files older than 7 days using 7za's command line utility. While most of the logic works fine, I am able to compress single file into single zip file.
The problem arises when I try to add all matching files to one zip file. Below is the code snippet:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strRun = objShell.Run(strCommand, 0, True)
Now as per the 2nd line, setting True would make sure the script will wait till command is finished executing. But the problem is 7za is exiting immediately and going to the next loop, processing the next file and since it tries to create same zip file, I get access denied error.
Can someone please help me to fix this?
I have also tested the scenario in command prompt. What I did was, execute below 2 commands simultaneously in separate prompts:
Prompt 1:
C:\7za.exe -mx=9 a test.zip c:\sample1.pdf
Prompt 2:
C:\7za.exe -mx=9 a test.zip c:\sample2.pdf
Prompt 2 resulted in following error:
Error: test.zip is not supported archive
System error:
The process cannot access the file because it is being used by another process.
This is the same error I am getting in my script and I need help in resolving this. Any pointers will be helpful!
UPDATE:
With the great pointers provided by both John and Ansgar, I was able to resolve this! It turned out to be a bug in my script! In my script, I included a check to see if the file is in use by any other process before processing it for archive. So I was checking this by opening the file for appending using:
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
But before proceeding to process the same file, I was not CLOSING it in the script, hence the error: The process cannot access the file because it is being used by another process
After I closed the file, all went well!
Thanks Again for all the great support I got here!
As a token of gratitude, I am sharing the whole script for anyone's use. Please note that I am not the original author of this, I gathered it from various sources and tweaked it a little bit to suit my needs.
Archive.vbs
Const ForAppending = 8 ' Constant for file lock check
Dim objFSO, objFolder, objFiles, objShell
Dim file, fileExt, fileName, strCommand, strRun, strFile
Dim SFolder, OFolder, Extension, DaysOld, sDate
'''' SET THESE VARIABLES! ''''
SFolder = "C:\SourceFolder\" 'Folder to look in
OFolder = "C:\OutputFolder\" 'Folder to put archives in
Extension = "pdf" 'Extension of files you want to zip
DaysOld = 1 'Zip files older than this many days
''''''''''''''''''''''''''''''
sDate = DatePart("yyyy",Date) & "-" & Right("0" & DatePart("m",Date), 2) & "-" & Right("0" & DatePart("d",Date), 2)
'Create object for playing with files
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create shell object for running commands
Set objShell = wscript.createObject("wscript.shell")
'Set folder to look in
Set objFolder = objFSO.GetFolder(SFolder)
'Get files in folder
Set objFiles = objFolder.Files
'Loop through the files
For Each file in objFiles
fileName = Split(file.Name, ".")
fileExt = fileName(UBound(fileName))
'See if it is the type of file we are looking for
If fileExt = Extension Then
'See if the file is older than the days chosen above
If DateDiff("d", file.DateLastModified, Now()) >= DaysOld Then
strFile = file.Path
'See if the file is available or in use
Set f = objFSO.OpenTextFile(strFile, ForAppending, True)
If Err.Number = 70 Then ' i.e. if file is locked
Else
f.close
strFName = objFSO.GetBaseName(file.name)
strCommand = "C:\7za.exe -mx=9 a " & OFolder & sDate & ".zip " & strFile
strRun = objShell.Run(strCommand, 0, True)
'wscript.echo strCommand ' un-comment this to check the file(s) being processed
'file.Delete ' un-comment this to delete the files after compressing.
End If
End If
End If
Next
'Cleanup
Set objFiles = Nothing
Set objFolder = Nothing
Set objFSO = Nothing
Set objShell = Nothing
wscript.Quit
===========================
Thanks
-Noman A.
Not quite what you asked for, but here's a batch script I use for a similar task in case that helps get you past of your immediate issue:
ArchiveScriptLog.Bat
::ensure we're in the right directory, then run the script & log the output
cls
pushd "c:\backup scripts"
ArchiveScript.bat > ArchiveScript.log
popd
ArchiveScript.bat
::Paths (must include the \ on the end). There must be no space between the equals and the value
::UNC paths are acceptable
Set FolderToBackup=F:\EnterpriseArchitect\Energy\
Set BackupPath=F:\EnterpriseArchitect\!ARCHIVE\
Set RemoteBackupPath=\\ukccojdep01wok\h$\Energy\cciobis01edc\
Set SevenZip=C:\Program Files (x86)\7-Zip\
::Get DATE in yyyymmdd format; done in two lines to make it easy to change the date format
FOR /F "TOKENS=2,3,4 DELIMS=/ " %%A IN ('echo %Date%') DO (SET mm=%%A&SET dd=%%B&SET yyyy=%%C)
SET strDate=%yyyy%%mm%%dd%
::Set the Backup File to be the backup path with the current date & .zip on the end
Set BackupFile=%BackupPath%%strDate%.zip
::create a zip containing the contents of folderToBackup
pushd %SevenZip%
7z a "%BackupFile%" "%FolderToBackup%"
popd
::go to the archive directory & copy all files in there to the remote location (this accounts for previous errors if the network were unavailable)
pushd "%BackupPath%"
move *.zip "%RemoteBackupPath%"
popd
::delete off backups in the remote location which are older than 90 days
pushd "%RemoteBackupPath%"
forfiles /D -90 /M *.zip /C "cmd /c del #file"
popd
Your command shouldn't return before 7za has finished its task (and it doesn't in my tests). Try changing your code to the following, so you can see what's going on:
strCommand = "7za.exe -mx=9 a " & ObjectFolder & sysDate & ".zip " & strFileName
strCommand = "%COMSPEC% /k " & strCommand
strRun = objShell.Run(strCommand, 1, True)
It may also be a good idea to quote the filenames:
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
strCommand = "7za.exe -mx=9 a " & qq(ObjectFolder & sysDate & ".zip") & " " _
& qq(strFileName)

Resources