Developer's Closet A place where I can put my PHP, SQL, Perl, JavaScript, and VBScript code.

26May/100
Using VBScript to Kill a Process in Windows

After listing a process, you may want to kill or terminate a process:

strComputer = "."
strProcess = "'iexplore.exe'"

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2") 

Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcess )

For Each objProcess in colProcess
	objProcess.Terminate()
	WScript.Echo "Killed Process: " & objProcess.Name & vbTab & objProcess.ProcessId
Next
26May/100
Using VBScript to List Processes in Windows

Just like ps, this VBScript will return the running processes. Just like using Task Manager. Very simple.

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")

For Each objProcessin objWMIService.InstancesOf("Win32_process")
   WScript.Echo objProcess.Name & vbTab & objProcess.ProcessId
Next

WScript.Echo "End of Process List"

Another method:

strComputer = "."

Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process")

For Each objProcess in colProcess
	WScript.Echo objProcess.Name & vbTab & objProcess.ProcessId
Next

WScript.Echo "End of Process List"
6May/100
List Scheduled Tasks from a Windows Server

This script will query a server and output a list of scheduled tasks as a csv (Excel) file. This file is useful when auditing servers.

Note: This script works only for Server 2003, Server 2008, and Windows XP (requires schtasks.exe).


Dim TimeStamp: TimeStamp = Right("0" & Month(now()), 2) & Right("0" & Day(now()), 2) & Right("0" & Year(now()), 2) & Right("0" & Hour(now()), 2) & Right("0" & Minute(now()), 2) & Right("0" & Second(now()), 2)

TmpFile = "C:\Temp\ScheduledTasks\schtasks.txt"
LogFile = "C:\Temp\ScheduledTasks\output_" & TimeStamp & ".csv"

servers = "SERVER-01,SERVER-02,SERVER-03,SERVER-04"
serverArr = Split(servers, ",")

Const ForReading = 1
Const ForWriting = 2

Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

cmdstr = "cmd /c echo >" & TmpFile
retval = objShell.Run(cmdstr, 1, True)

For Each Computer In serverArr
'WScript.Echo Computer

If Computer  "" Then
    cmdstr = "cmd /c schtasks /query /s \\" & Computer & " /v /fo list >>" & TmpFile
Else
    cmdstr = "cmd /c schtasks /query /v /fo list >>" & TmpFile
End If
retval = objShell.Run(cmdstr, 1, True)
Next

Dim objLog: Set objLog = objFSO.CreateTextFile(LogFile)
Set objLog = Nothing
Set objLog = objFSO.OpenTextFile(LogFile, 2)

If objFSO.FileExists(TmpFile) Then
    Dim linecount, objFSO, objFile, ln, strLine

    linecount = 0 
servercount = 0
 
    Set objFile = objFSO.OpenTextFile(TmpFile, ForReading)
    Do Until objFile.AtEndOfStream
        strLine = Trim(objFile.Readline)

        If Left(strLine, 9) = "HostName:" Then
            hostname = Mid(strLine, 39)
            'wscript.echo vbTab & ""
If (servercount = 0) Then 
objLog.Write """HostName"",""TaskName"",""Next Run Time"",""Status"",""Logon Mode"",""Last Run Time"",""Last Result"",""Creator"",""Schedule"",""Task To Run"",""Start In"",""Comment"",""Scheduled Task State"",""Scheduled Type"",""Start Time"",""Start Date"",""End Date"",""Days"",""Months"",""Run As User"",""Delete Task If Not Rescheduled"",""Stop Task If Runs X Hours and X Mins"",""Repeat: Every"",""Repeat: Until: Time"",""Repeat: Until: Duration"",""Repeat: Stop If Still Running"",""Idle Time"",""Power Management"""
End If
objLog.Write vbCrLf
servercount = servercount + 1
     	 objLog.Write """" & hostname & """"
        ElseIf Left(strLine, 9) = "TaskName:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
            'wscript.echo vbTab & vbTab & "" & hostname & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 14) = "Next Run Time:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 7) = "Status:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """" & "," & """" & "Interactive/Background" & """"
     
        ElseIf Left(strLine, 14) = "Last Run Time:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 12) = "Last Result:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 8) = "Creator:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 9) = "Schedule:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 12) = "Task To Run:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 9) = "Start In:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 8) = "Comment:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 21) = "Scheduled Task State:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 15) = "Scheduled Type:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 11) = "Start Time:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 11) = "Start Date:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 9) = "End Date:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 5) = "Days:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
     
        ElseIf Left(strLine, 7) = "Months:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 12) = "Run As User:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 31) = "Delete Task If Not Rescheduled:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 37) = "Stop Task If Runs X Hours and X Mins:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 14) = "Repeat: Every:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 20) = "Repeat: Until: Time:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 24) = "Repeat: Until: Duration:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 30) = "Repeat: Stop If Still Running:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 10) = "Idle Time:" Then
            'wscript.echo vbTab & vbTab & "" & Mid(strLine, 39) & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        ElseIf Left(strLine, 17) = "Power Management:" Then
            'wscript.echo vbTab & ""
objLog.Write "," & """" & Mid(strLine, 39) & """"
        End If
        linecount = linecount + 1
    Loop
    objFile.Close
    Set objFSO = Nothing
 
Else
    wscript.echo "fail: file not found"
End If

WScript.Echo "End"
13Apr/100
Display Process List Using VBScript

This great VBScript script will display running processes on a Windows workstation. The script queries the Win32_Process from a WMI Object using ExecQuery then loops through the results. To access the process list on another server, set the strComputer variable to the server's name.

Option Explicit
Dim objWMIService, objProcess, colProcess, strComputer, strList

strComputer = "."

Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery("Select * from Win32_Process")

For Each objProcess in colProcess
	strList = strList & vbCr & objProcess.Name
Next

WSCript.Echo strList
WScript.Quit
18Feb/101
Move Your Mouse Using VBScript and Excel

This script uses the GetMessagePos and SetCursorPos Windows API functions to move your mouse. The script will first get the current position of the mouse by calling GetMessagePos. Next, the script will move the mouse using SetCursorPos. All this is done through an Excel macro. You can call Excel macros through the ExecuteExcel4Macro method. Needless to say, Excel must be installed locally for this script to work. I've found this script very useful for fooling screensavers.

Option Explicit
Dim Excel, GetMessagePos, x, y, Count, Position

Do While Count < 10
	Set Excel = Wscript.CreateObject("Excel.Application")

	GetMessagePos = excel.ExecuteExcel4Macro("CALL(""user32"",""GetMessagePos"",""J"")")

	x = CLng("&H" & Right(Hex(GetMessagePos), 4))
	y = CLng("&H" & Left(Hex(GetMessagePos), (Len(Hex(GetMessagePos)) - 4)))
	If Count MOD 2 = 0 Then
		Position = "- 30"
	Else
		Position = "+ 30"
	End If
	Excel.ExecuteExcel4Macro("CALL(""user32"",""SetCursorPos"",""JJJ""," & x & " " & Position & "," & y & " " & Position & ")")

	WScript.Sleep(100)
	Count = Count + 1

Loop
WScript.Echo "Program Ended"

Reference: http://msdn.microsoft.com/en-us/library/aa191494%28office.10%29.aspx

2Jan/101
How to Run a Script within VBScript

This is a useful script to call another script within VBScript. Using the Run method within the WshShell object allows you to call any script within a VBScript. The Run method takes three parameters, script name, window style (how the application will open), and whether or not to wait for the script to end before continuing. The script below calls a script, hides the script on open, and waits for the script to complete before continuing. Uses a simple return value to test for success/fail.

Dim ReturnValue
Dim objShell: Set objShell = CreateObject("WScript.Shell")
ReturnValue = objShell.Run("C:\Script.exe /p=passvariables",0,true)
WScript.Echo "ReturnValue: " & ReturnValue
If (ReturnValue  0) Then
	WScript.Echo "Failed with error: " & ReturnValue
Else
	WScript.Echo "Success with return value: " & ReturnValue
End If

Reference: http://msdn.microsoft.com/en-us/library/d5fk67ky%28v=VS.85%29.aspx

Tagged as: , 1 Comment
19Nov/090
Send an Email with VBScript

Another really easy script. This script will send an email. As I automate tasks, I like to build an html log file and email the results of the script. You can also send an email as text.

' The following procedure will take an email address and content and complete an email
Sub EmailSend(EmailAddressTo,EmailAddressCc,EmailAddressBcc,EmailAddressFrom,Subject,Content)
	' Send the email report
	Dim cdoMessage, cdoConfig, sch: sch = "http://schemas.microsoft.com/cdo/configuration/" 
	
	Set cdoConfig = CreateObject("CDO.Configuration") 
	
	With cdoConfig.Fields 
		.Item(sch & "sendusing") = 2 ' cdoSendUsingPort 
		.Item(sch & "smtpserver") = "exchangeserver" 
		.Item(sch & "smtpserverport") = 25 
		.update 
	End With 
	
	Set cdoMessage = CreateObject("CDO.Message") 
	
	With cdoMessage 
		Set .Configuration = cdoConfig 
		.From = EmailAddressFrom 
		.To = EmailAddressTo 
		.Cc = EmailAddressCc
		.Bcc = EmailAddressBcc
		.Subject = Subject
		.HTMLBody = Content
		'.TextBody = Content 
		.Send 
	End With 
	
	' Cleanup
	Set cdoMessage = Nothing 
	Set cdoConfig = Nothing 
End Sub

This code will call the sub:

Set LogFile = objFSO.OpenTextFile(sCurPath & "\Logs\" & LogFileName, 1)
Content = LogFile.ReadAll
LogFile.Close 

EmailSend "email@address.com,email2@address.com","ccemail@address.com","bccemail@address.com","fromemail@address.com","Email Subject",Content
26Aug/090
Retrieve Model and Serial Number with VBScript

Simple script to retrieve information about a workstation or hardware.

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colSettings = objWMIService.ExecQuery _
    ("Select * from Win32_ComputerSystem")
For Each objComputer in colSettings 
    Wscript.Echo "System Name: " & objComputer.Name
    Wscript.Echo "System Manufacturer: " & objComputer.Manufacturer
    Wscript.Echo "System Model: " & objComputer.Model
Next

Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_ComputerSystemProduct") 
For Each objItem in colItems 
    Wscript.Echo "Serial Number: " & objItem.IdentifyingNumber
Next
16Aug/090
Pass Parameters from a Windows Batch Script to VBScript

It can be very useful to pass parameters from a Windows Batch Script to VBScript. For this to work, a user will pass parameters to a batch script, the batch script will pass them to the VBScript script using cscript and the script will output the results. This will allow you to use the power of VBScript within the simple framework of a batch script.

Create a batch script named Call.bat. Add this code to the script:

cscript Script.vbe %1 %2

Create a VBScript script named Script.vbe. Add this code to the script:

Option Explicit
Dim args, strOutOne, strOutTwo
set args = Wscript.arguments

strOutOne= args(0)
strOutTwo= args(1)

WScript.Echo strOutOne
WScript.Echo strOutTwo

Finally, run the batch script:

Call.bat hello world

14Aug/092
Call VBScript from a Windows Batch Script

This very easy bit of code will call a VBScript script from a Windows Batch Script:

call script.vbs