?
Solved

Batch File to VBScript

Posted on 2011-04-21
14
Medium Priority
?
880 Views
Last Modified: 2012-05-11
Hi there,

I need to convert the following batch file to VBscript.

Thanks for your help,
Rene

 
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION


SET TMP1=%~n0_TMP1.txt
SET TMP2=%~n0_TMP2.txt
SET WaitTime=60

SET LogFolder=.\LOGS
SET LogFile=%LogFolder%\%~n0.log

IF EXIST "%TMP1%" DEL "%TMP1%"
IF EXIST "%TMP2%" DEL "%TMP2%"

ECHO ^>READING RUNNING TASKS FOR THE FIRST TIME
CALL :GetDateTime
(FOR /F "tokens=1,9* delims=," %%A IN ('TASKLIST /NH /v /FO CSV /FI "USERNAME ne NT AUTHORITY\SYSTEM"') DO ECHO %%~A,%%~B)>>"%TMP1%"



:Home

REM READING INI FILE
	IF EXIST "%~n0.ini" FOR /F "tokens=1,2 delims==" %%A IN (%~n0.ini) DO SET %%A=%%B

IF NOT EXIST "%LogFolder%" MD "%LogFolder%"

ECHO WAIT TIME=%WaitTime%
ECHO LOG FOLDER="%LogFolder%"
ECHO LOG FILE="%LogFile%"
ECHO.

ECHO ^>Waiting
CHOICE /D Y /T 05 >NUL
CLS

ECHO ^>READING CURRENT TASKS
(FOR /F "tokens=1,9* delims=," %%A IN ('TASKLIST /NH /v /FO CSV /FI "USERNAME ne NT AUTHORITY\SYSTEM"') DO ECHO %%~A,%%~B)>>"%TMP2%"

CALL :GetDateTime

ECHO ^>ARE THERE NEW RUNNERS?
REM ARE THERE NEW RUNNERS?
FOR /F "tokens=1,2 delims=," %%A IN ('findstr /V /G:"%TMP1%" "%TMP2%"') DO IF "%%B" NEQ "N/D" ECHO %TheDate%,%TheTime%,+,%username%,%%A,%%B>>%LogFile%

ECHO ^>ARE THERE CLOSED RUNNERS?
REM ARE THERE CLOSED RUNNERS?
FOR /F "tokens=1,2 delims=," %%A IN ('findstr /V /G:"%TMP2%" "%TMP1%"') DO IF "%%B" NEQ "N/D" ECHO %TheDate%,%TheTime%,-,%username%,%%A,%%B>>%LogFile%

MOVE /Y "%TMP2%" "%TMP1%">NUL

GOTO Home


:GetDateTime
REM READ DATE
	FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
		IF %%A GTR 0 (
		SET Day=0%%A
		SET Hour=0%%B
		SET Min=0%%C
		SET Month=0%%D
		SET Sec=0%%E
		SET Year=%%F
	)
)
SET Day=%Day:~-2%
SET Hour=%Hour:~-2%
SET Min=%Min:~-2%
SET Month=%Month:~-2%
SET Sec=%Sec:~-2%

SET TheDate=%Year%-%Month%-%Day%
SET TheTime=%Hour%.%Min%.%Sec%

EXIT /b

Open in new window

0
Comment
Question by:ReneGe
  • 9
  • 5
14 Comments
 
LVL 1

Expert Comment

by:ovolume
ID: 35475954
Microsoft publishes several utilities to monitor processes. See http://technet.microsoft.com/en-us/sysinternals/.
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35476008
Thanks ovolume, but none of them does what I need to do.

Cheers,
Rene
0
 
LVL 1

Expert Comment

by:ovolume
ID: 35478816
The included batch instructions create a log file listing any new or terminated processes. Is that all that is needed or is additional functionality desired?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Author Comment

by:ReneGe
ID: 35479032
Yep!

I need to have this in VBScript because with a batch file, I was unable to get the unicode french caracters to the output file correctly.

Also, I need their Window Title and if possible, to get this info from a remote Domain PC as well.

By the way, I'v tried to get the remote window title using WMIC, tasklist, psexec and Power Shell v2.0 and no luck here.

Thanks for helping
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35509277
Just wanted to know if you were on it?

Thanks and cheers,
Rene
0
 
LVL 1

Expert Comment

by:ovolume
ID: 35509495
Yes, I will have a working VBScript for you this week.
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35509735
Thanks a million!
0
 
LVL 1

Accepted Solution

by:
ovolume earned 2000 total points
ID: 35691774
My first attempt to emulate the batch commands in VBScript is embedded below. Replace variable strServer with remote DC server name to monitor processes from it. It's basic, however additional functionality can be added easily. As long as the monitored server is on, the script will run indefinitely. The wscript.exe process has to be terminated manually on the computer running the script to stop logging. Let me know if it is close to what you're looking for.

 
Option Explicit

'Initialize Script-level Variables 
Const ForReading = 1, ForAppending = 8
Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Dim strLogLocation
Dim objFSO
Dim arrServers
Dim strServer
Dim strLog

Set objFSO = CreateObject("Scripting.FileSystemObject")

strServer = "."
strLogLocation = ".\LOGS\" & strServer & "_Processes.log"

'*************************************************************************
' Main
'*************************************************************************

Call MonitorProcesses

'*************************************************************************
' Define Functions and Subroutines
'*************************************************************************
Sub OpenLog()
	Dim strLogFolder
	strLogFolder = ".\LOGS"
	If NOT objFSO.FolderExists(strLogFolder) Then 
		objFSO.CreateFolder(strLogFolder)
	End If 
	Set strLog = objFSO.OpenTextFile(strLogLocation, ForAppending, True)
End Sub

Sub MonitorProcesses()
	Dim objWMIService
	Dim colCachedProcesses, objCachedProcess, colActiveProcesses, objActiveProcess
	Dim arrCachedProcesses, arrActiveProcesses, arrCachedOwner, arrActiveOwner
	Dim strUsername, strOwner
	Dim colCachedKeys, objCachedKey, colActiveKeys, objActiveKey
		
	Call OpenLog
	
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strServer & "\root\CIMV2")
	'Create Dictionary Objects to Store PID, Process Pairs
	Set arrCachedProcesses = CreateObject("Scripting.Dictionary")
	Set arrActiveProcesses = CreateObject("Scripting.Dictionary")
	'Create Dictionary Objects to Store PID, Owner Pairs
	Set arrActiveOwner = CreateObject("Scripting.Dictionary")
	Set arrCachedOwner = CreateObject("Scripting.Dictionary")
	'Collect Initial Win32 Processes
	Set colCachedProcesses = objWMIService.ExecQuery ("SELECT * FROM Win32_Process", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	'Cache Initial Processes in Process and Owner Arrays 
	For Each objCachedProcess in colCachedProcesses
		strOwner = objCachedProcess.GetOwner(strUsername)
		arrCachedProcesses.Add objCachedProcess.ProcessId, objCachedProcess.Caption
		arrCachedOwner.Add objCachedProcess.ProcessId, strUsername
	Next
	
	Do While arrCachedProcesses.Count > 0
		On Error Resume Next
		'Collect Active Win32 Processes
		Set colActiveProcesses = objWMIService.ExecQuery ("SELECT * FROM Win32_Process", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
		'Clear Active Process and Owner Arrays
		arrActiveProcesses.RemoveAll
		arrActiveOwner.RemoveAll
		'Populate Active Process and Owner Arrays
		For Each objActiveProcess in colActiveProcesses
			strOwner = objActiveProcess.GetOwner(strUsername)
			arrActiveProcesses.Add objActiveProcess.ProcessId, objActiveProcess.Caption
			arrActiveOwner.Add objActiveProcess.ProcessId, strUsername
		Next
		'Compare Cached Array Keys to Active Processes to Determine Terminiated Processes
		colCachedKeys = arrCachedProcesses.Keys
		For Each objCachedKey in colCachedKeys
			If Not arrActiveProcesses.Exists(objCachedKey) Then
				strLog.Write  Now() & ",-," & arrCachedOwner(objCachedKey) & "," & arrCachedProcesses(objCachedKey)  
				strLog.Write vbCrLf
			End If
		Next	
		'Compare Active Array Keys to Cached Processes to Determine New Processes
		colActiveKeys = arrActiveProcesses.Keys
		For Each objActiveKey in colActiveKeys
			If Not arrCachedProcesses.Exists(objActiveKey) Then
				strLog.Write Now() & ",+," & arrActiveOwner(objActiveKey) & "," & arrActiveProcesses(objActiveKey) 
				strLog.Write vbCrLf
			End If
		Next
		'Cache Active Processes 
		arrCachedProcesses.RemoveAll
		arrCachedOwner.RemoveAll
		For Each objActiveKey in colActiveKeys
			arrCachedProcesses.Add objActiveKey, arrActiveProcesses(objActiveKey)
			arrCachedOwner.Add objActiveKey, arrActiveOwner(objActiveKey)
		Next
	Loop
	strLog.close
End Sub

Open in new window

0
 
LVL 10

Author Comment

by:ReneGe
ID: 35699530
I tried it and it did not work. I'll give you details a bit later.

Thanks a million,
Rene
0
 
LVL 1

Expert Comment

by:ovolume
ID: 35702754
Did it work as-is, without replacing the strServer variable (i.e., strServer = ".")? I ran the script successfully on Windows 7 32bit, XP and Server 2003 R2.  
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35702768
I replaced the wrong strServer. What a bummer!!

I'll try it right now and let you know.
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35702860
Ok, it does work. Sorry for that.

Issues:
-I need to log changes that occured every 15 seconds
-Need to log the Window Title
-Need to laungh it with cscript as (for example): cscript "monitorapps.vbs" "pcname1"
-When launghing, no computer name is defined, monitor apps on the PC it's running.

Thanks a trillion
0
 
LVL 10

Author Comment

by:ReneGe
ID: 35702864
Wow, I missed my las one. lets try again:
-When launghing, if no computer name is defined, it must monitor the apps on the PC it's running.

0
 
LVL 10

Author Closing Comment

by:ReneGe
ID: 35790786
Thanks a million for your help.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
Suggested Courses
Course of the Month13 days, 15 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question