I’ve had the pleasure of meeting Trevor Sullivan when I convinced him he should learn all about SQL Server. Not really, but we did chat it up on Twitter and decided to both go to Cleveland for an intro on SQL Server 2008 R2. Little did I know what he was working on. Quite simply one of the coolest projects I’ve used from Codeplex. Trevor has created PowerEvents! I’ll admit, some of it is way over my head at the moment. It’s directly related to how much I really know about WMI, but I feel that’s about to change drastically.
I posted a tweet earlier about what I’ve created with PowerEvents. Actually, I feel as if it would be a best practice for the ActiveScriptEventConsumer. You can be the judge of that . Since it’s almost impossible to see what you’ve created as an Event Consumer, I’ve simply created only one: ActiveScriptEventConsumer. That way I don’t have to worry about what has been added under the hood to WMI. All I have to do is tweak the script that is fired when the event occurs. So, I’ve built a basic script that looks for the arguments you have passed to it. Based on these arguments, you can dynamically call different scripts or functions. Pretty slick, eh? Here’s a basic script that will email two different people based on what the WMI query results are.
Option ExplicitConst strFrom = "firstname.lastname@example.org"Const strMailserver = "smtp.example.com"Const strSchema = "http://schemas.microsoft.com/cdo/configuration/"Dim objArgs, objEmailDim strProcessName, strSubject, strBody, strTo'Get arguments from command lineset objArgs = WScript.ArgumentsstrProcessName = WScript.Arguments(0)strSubject = WScript.Arguments(1)strBody = Wscript.Arguments(2)'Dynamically change the email recipient'Or even change the function to be called'Or call a completely different script: .bat, .vbs, .ps1'Endless possibilitiesIf strProcessName = "NotePad.exe" ThenstrTo = "email@example.com"ElseIf strProcessName = "Outlook.exe" ThenstrTo = "firstname.lastname@example.org"End If'Call to send email, but many different functions could be within this script and'dynamically called based on argumentsCall SendEmail(strSubject, strBody)'Function(s)Sub SendEmail(Subject, Body)Set objEmail = CreateObject("CDO.Message")objEmail.From = strFromobjEmail.To = strToobjEmail.Subject = SubjectobjEmail.Textbody = BodyobjEmail.Configuration.Fields.Item _(strSchema & "sendusing") = 2objEmail.Configuration.Fields.Item _(strSchema & "smtpserver") = strMailserverobjEmail.Configuration.Fields.Item _(strSchema & "smtpserverport") = 25objEmail.Configuration.Fields.UpdateobjEmail.SendEnd Sub'Clean up varsset strProcessName = nothingset strSubject = nothingset strBody = nothing
I hope you find this useful. I’m brand new to creating PowerEvents, but I do feel this is the best way to handle scripting based on events. Feel free to post a comment if I’m an idiot and there is a much easier way…