Over the years I've occasionally found it necessary to employ scripts in a fashion that makes monitoring their progress difficult or nearly impossible, given that I suffer from the human fallibility known as "needing to sleep". So to counteract this weakness and sustain the illusion that I'm some kind of omniscient IT-Deity I long ago looked into developing a way to have scripts communicate with me using that most ubiquitous of channels; e-mail.
No great trick, I know. There are tons of examples out there that will show you how to send an e-mail via script and this one isn't too dissimilar to the rest. The difference here would be in the way that I typically employ this trick, which is not something I've personally seen posted anywhere else; as part of error handling.
Granted I would suggest using this sparingly lest you be inundated with little pops and pings from your scripts, but including something like this in those mission-critical scripts that have to run at all hours of the day or night can help you rest a little easier; or not, depending on the results. As a bonus the same function can be used to send an e-mail at any time throughout the script, so "start and stop" notifications can be configured just as easily if need be.
This particular sub is configured to work with Gmail as the sending account, primarily because it's free and easily accessible. If you're not able to use a web-accessible service you can pretty easily modify this to run off of your company's exchange system (or what have you).
The example below is straight forward; I purposely generate an error by making an illegal assignment to kick off the error checking routine and send an e-mail notification. I also stop the script from executing further, to keep the damage to a minimum (hopefully).
On Error Resume Next
Set Now = "This Value" 'Throw an error to be caught
if Err.Number <> 0 Then
msgSubject = Err.Description & " : " & Err.Number
msgText = Err.Description & vbCrlf
msgText = msgText & Err.Number & vbCrlf
msgText = msgText & Err.Source & vbCrlf
msgText = msgText & "If you get this e-mail, we're good to go!"
Call sendError("colonelhammer@yahoo.com", msgSubject, msgText)
Wscript.Quit
End if
msgbox "If you see this, I'm in trouble"
sub sendError(toField, subjectLine, msgBody)
Set objMsg = CreateObject("CDO.Message")
'Build your e-mail.
objMsg.From = "YourAddress@gmail.com" '<----Generally needs to match the address you're sending from!
objMsg.To = toField
objMsg.Subject = subjectLine
objMsg.TextBody = msgBody
'------------Back-end Configuration information for the remote SMTP server----------
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'SMTP Server, name or by IP address.
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
'Type of authentication
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
'Your UserID on the SMTP server
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "YourAddress@gmail.com@gmail.com"
'Your password on the SMTP server
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "YourPaswordHere"
'Server port (typically 25)
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'Use SSL for the connection (False or True)
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
'Connection Timeout in seconds
objMsg.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objMsg.Configuration.Fields.Update
'------------Back-end Configuration information for the remote SMTP server----------
objMsg.Send
End Sub
Enjoy,
Code Snippets, scripts and functions that I've found useful in my rather diverse pursuits.
Showing posts with label VBScript. Show all posts
Showing posts with label VBScript. Show all posts
Wednesday, October 6, 2010
Friday, October 1, 2010
VBScript: How to print a document after a delay
Have you ever worked in a crowded office with public and shared printers, but needed to print something personal or confidential? If you have then you've know that moment of gut-clenching, cold-sweating nausea that accompanies the old "hit print and run like hell to the printer" routine. I've had to do it in the past, and I've hated it.
So, here's a quick little script that can make life a little easier. When you run the script it will prompt you for a number of seconds to wait and the path to a Word Document (.doc) that you want to print. Just enter it in the format of "Seconds, FilePath" such as 30, C:/Temp/Test1.doc and hit enter. The script will then wait the number of seconds specified, open Word and print your document to your default printer, giving you plenty of time to walk over and stake your claim to privacy.
'-----------------------------------------------------------------
Input1 = InputBox("Seconds, FilePath",, "30, C:/Temp/Test1.doc")
findComma = Instr(Input1, ", ")-1
Seconds = left(Input1, findComma)
FilePath = right(Input1, Len(Input1)-(findComma +2))
call delayPrint(Seconds, FilePath)
function delayPrint(Seconds, FilePath)
WScript.Sleep Seconds * 1000
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(FilePath)
objDoc.PrintOut()
objWord.Quit
end function
'-----------------------------------------------------------------
Enjoy,
So, here's a quick little script that can make life a little easier. When you run the script it will prompt you for a number of seconds to wait and the path to a Word Document (.doc) that you want to print. Just enter it in the format of "Seconds, FilePath" such as 30, C:/Temp/Test1.doc and hit enter. The script will then wait the number of seconds specified, open Word and print your document to your default printer, giving you plenty of time to walk over and stake your claim to privacy.
'-----------------------------------------------------------------
Input1 = InputBox("Seconds, FilePath",, "30, C:/Temp/Test1.doc")
findComma = Instr(Input1, ", ")-1
Seconds = left(Input1, findComma)
FilePath = right(Input1, Len(Input1)-(findComma +2))
call delayPrint(Seconds, FilePath)
function delayPrint(Seconds, FilePath)
WScript.Sleep Seconds * 1000
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(FilePath)
objDoc.PrintOut()
objWord.Quit
end function
'-----------------------------------------------------------------
Enjoy,
VBScript: How to stop a VBScript immediately, or terminate another running process.
Ok, we've all done it. You write a script, you think it's the bomb....you click run and realize...oops. Whatever the reason, you want to kill that little sucker and if you're unlucky enough to be running a script that moves the mouse and sends key strokes then scrambling to open taskmanager and find wscript.exe is more of a pain than it's worth.
With a little forward planning you can be prepared. Just make a copy of this script and keep a shortcut to it handy (I keep one in the quick launch bar for one-click-emergencies).
'-----------------------------------------------------------
Option Explicit
Dim objWMI, objProc, colProc
Dim strComputer, strProc
strComputer = "."
strProc = "'wscript.exe'"
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProc = objWMI.ExecQuery _
("Select * from Win32_Process Where Name = " & strProc )
For Each objProc in colProc
objProc.Terminate()
Next
'-----------------------------------------------------------
Of course this same script could be modified to terminate any running process easily enough. The only real caveat is that whatever value you pass to strProc would need to be encapsulated in single quotes, or you would need to change the ExecQuery string to include those automatically. Ah heck, here you go.
function killProc(strProc)
Dim objWMI, objProc, colProc, strComputer
strProc = "'" & strProc & "'"
strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProc = objWMI.ExecQuery _
("Select * from Win32_Process Where Name = " & strProc )
For Each objProc in colProc
objProc.Terminate()
Next
end function
Enjoy,
With a little forward planning you can be prepared. Just make a copy of this script and keep a shortcut to it handy (I keep one in the quick launch bar for one-click-emergencies).
'-----------------------------------------------------------
Option Explicit
Dim objWMI, objProc, colProc
Dim strComputer, strProc
strComputer = "."
strProc = "'wscript.exe'"
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProc = objWMI.ExecQuery _
("Select * from Win32_Process Where Name = " & strProc )
For Each objProc in colProc
objProc.Terminate()
Next
'-----------------------------------------------------------
Of course this same script could be modified to terminate any running process easily enough. The only real caveat is that whatever value you pass to strProc would need to be encapsulated in single quotes, or you would need to change the ExecQuery string to include those automatically. Ah heck, here you go.
function killProc(strProc)
Dim objWMI, objProc, colProc, strComputer
strProc = "'" & strProc & "'"
strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProc = objWMI.ExecQuery _
("Select * from Win32_Process Where Name = " & strProc )
For Each objProc in colProc
objProc.Terminate()
Next
end function
Enjoy,
VBScript: Easy output to a text file
When your script generates output a msgbox is seldom sufficient, especially if you want to maintain some kind of logfile or history.
Here are a couple of classes I wrote that make exporting output to a file simple and repeatable. These functions log text to a file one line at a time, with a return between each line. Not ideal for large output but sufficient for light to moderate logging needs.
'This version send output to a file in the same directory as then executing script,
'with a name the same as the script_Log.txt
Class Logger
Sub logThis(txtString)
Set objFSO = Createobject("Scripting.FileSystemObject")
objLogFile = Left(wscript.scriptname, Len(wscript.scriptname)-4) & "_Log.txt"
Set objfile1 = objFSO.OpenTextFile(objLogFile, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub
end class
'Or if you need a little more flexibility as to where to put the file.
Class openLogger
Sub logThis(txtString, filePath)
Set objFSO = Createobject("Scripting.FileSystemObject")
Set objfile1 = objFSO.OpenTextFile(filePath, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub
end class
To use one of these in a script, paste the class code somewhere at the bottom of the script and then define a variable as a member of that class in your main function and call the class sub.
Example, if you want to send the text "Computername: MZZ1005AH" to a text file you would do the following.
Set Worker = New Logger
Worker.logThis("Computername: MZZ1005AH")
Not flashy, but functional.
Here are a couple of classes I wrote that make exporting output to a file simple and repeatable. These functions log text to a file one line at a time, with a return between each line. Not ideal for large output but sufficient for light to moderate logging needs.
'This version send output to a file in the same directory as then executing script,
'with a name the same as the script_Log.txt
Class Logger
Sub logThis(txtString)
Set objFSO = Createobject("Scripting.FileSystemObject")
objLogFile = Left(wscript.scriptname, Len(wscript.scriptname)-4) & "_Log.txt"
Set objfile1 = objFSO.OpenTextFile(objLogFile, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub
end class
'Or if you need a little more flexibility as to where to put the file.
Class openLogger
Sub logThis(txtString, filePath)
Set objFSO = Createobject("Scripting.FileSystemObject")
Set objfile1 = objFSO.OpenTextFile(filePath, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub
end class
To use one of these in a script, paste the class code somewhere at the bottom of the script and then define a variable as a member of that class in your main function and call the class sub.
Example, if you want to send the text "Computername: MZZ1005AH" to a text file you would do the following.
Set Worker = New Logger
Worker.logThis("Computername: MZZ1005AH")
Not flashy, but functional.
VBScript: Dynamically pull the current path of the script.
Sometimes you need to know where a script is living, without having to change a hard coded value when you deploy it. The following code is a cheap and easy way to find the current path where the script resides.
You can get the full script path, including the name of the script file by accessing the wscript object.
wscript.scriptfullname
Or to get the folder it's currently living in, minus the name:
function scriptPath()
Full_Path = wscript.scriptfullname
Name1 = wscript.scriptname
Path = Left(Full_Path, Len(Full_Path) - Len(Name1))
scriptPath = Path
end function
You can get the full script path, including the name of the script file by accessing the wscript object.
wscript.scriptfullname
Or to get the folder it's currently living in, minus the name:
function scriptPath()
Full_Path = wscript.scriptfullname
Name1 = wscript.scriptname
Path = Left(Full_Path, Len(Full_Path) - Len(Name1))
scriptPath = Path
end function
Thursday, August 21, 2008
VBScript: How to Lock a Workstation
I'm not a huge fan of VBScript but occasionally I find it a useful tool to employ. I like the fact that it gives me the ability to make a quick, double-click-and-take-action solution, all while using the simplest of code compliers out there; Notepad!
As a quick example, this code can be used to lock a workstation. To create the script just open a new text document in Notepad (not word, if you please) and enter the following:
"""""""Start Code""""""""""""""
On Error Resume Next
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "%windir%\System32\rundll32.exe user32.dll,LockWorkStation"
"""""""End Code"""""""""""""""
Save the file and then change the file extension from .txt to .vbs and there you have it.
(Note, some system admins lock out the .vbs file extension for safety and security reasons so this may or may not work where you work, as it were.)
I typically place a shortcut to this little script in my quick launch bar and use it as a "one click and walk away" convenience at work. Once you launch the script there's pretty much nothing short of a full OS failure that's going to stop the workstation from locking. Comes in handy when you're constantly dashing away from your desk to put out fires.
As a quick example, this code can be used to lock a workstation. To create the script just open a new text document in Notepad (not word, if you please) and enter the following:
"""""""Start Code""""""""""""""
On Error Resume Next
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "%windir%\System32\rundll32.exe user32.dll,LockWorkStation"
"""""""End Code"""""""""""""""
Save the file and then change the file extension from .txt to .vbs and there you have it.
(Note, some system admins lock out the .vbs file extension for safety and security reasons so this may or may not work where you work, as it were.)
I typically place a shortcut to this little script in my quick launch bar and use it as a "one click and walk away" convenience at work. Once you launch the script there's pretty much nothing short of a full OS failure that's going to stop the workstation from locking. Comes in handy when you're constantly dashing away from your desk to put out fires.
Subscribe to:
Posts (Atom)