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

27Jun/110
Escalate Privileges in Windows 7

Windows 7 requires you to escalate privileges before running your VBSCript. The following script reopens the script with administration privileges.

If WScript.Arguments.length = 0 Then
Set objShell = CreateObject("Shell.Application")
' pass an argument with leading blank space (uac)
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
' put your code here
End If
WScript.Quit

Filed under: VBScript, Windows No Comments
19Jul/100
VBScript and WMI to stop and restart a running service

Option Explicit
Dim objWMIService, objItem, objService
Dim colListOfServices, strComputer, strService, intSleep
strComputer = "."
intSleep = 15000
WScript.Echo "Click OK to begin"

'On Error Resume Next
' strService is case sensitive
strService = " 'AdobeARMservice' "
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service Where Name ="_
& strService & " ")
For Each objService in colListOfServices
objService.StopService()
WScript.Echo "The " & strService & " service has been stopped"
WScript.Sleep intSleep
objService.StartService()
Next
WScript.Echo "The " & strService & " service has Started"
WScript.Quit

Filed under: VBScript, Windows No Comments
2Jul/100
Query a List of Servers from Active Directory

I needed a list of all servers listed in AD. There are many scripts out there that do this, but they didn't quite fit my needs, so I put together one from a few different scripts.

strADDomainName = "domainname.com"

strBase = ";"
Set objFSO = CreateObject ("Scripting.FileSystemObject")
Set objFileOut = objFSO.OpenTextFile ("listofservers.txt", 2, True)

strFilter = "(&(objectclass=computer)(objectcategory=computer)(operatingSystem=*Server*)(cn=*));"
strAttrs = "cn;"
strScope = "subtree"
Set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"

Set objRS = objConn.Execute(strBase & strFilter & strAttrs & strScope)
objRS.MoveFirst
While Not objRS.EOF
	WScript.Echo objRS.Fields(0).Value
	objFileOut.WriteLine(LCase(objRS.Fields(0).Value) & ", " & LCase(objRS.Fields(0).Value) & "." & strADDomainName)
	objRS.MoveNext
WEnd

objFileOut.Close
Set objFileOut = Nothing
Set objFSO = Nothing

Reference: http://www.intellipool.se/forum/index.php?showtopic=849

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