VisualBasic Script

VisualBasic Script check_msmq.wsf

Project Objective:
Create a Nagios addon to be run with NRPE/NSClient++ that checks the Microsoft Message Queue for “stuck” messages.

Problem to be solved:
Increased monitoring of Microsoft Message Queue. Get notified when messages are not leaving message queue.

'***********************************************************************
' "check_msmq.wsf"
'
' Written by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'
' If you edit please keep my name as an original author and
' keep me apprised of the changes, see email address above.
' This code may not be used for commercial purposes.
' You the executor,runner,user accept all liability.
' This code comes with ABSOLUTELY NO WARRANTY.
' You may redistribute copies of the code under the terms of the GPL v2.
' -----------------------------------------------------------------------
' 2010.09.26 ver 1.0
' Checks number of messages in the Microsoft Message Queue. If warning or
' critical thresholds are reached number of messages are outputted.
'************************************************************************

<job>
<runtime>
  <description>

check_msmq (nrpe_nt-plugin) 1.0
This nrpe_nt plugin come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License.

  </description>
    <named
      name="h"
      helpstring="Help"
      type="simple"
      required="false"
    />
  />

  <example>

  You do not need a string for this plugin.

 Checks number of messages in the Microsoft Message Queue. If warning or
 critical thresholds are reached number of messages are outputted.

  Usage: command [check_msmq]
  c:Windowssystem32cscript.exe //NoLogo //T:10 check_msmq.wsf

  </example>

</runtime>

<script language="VBScript">

'*******************************************************************
' Help
'*******************************************************************
If Wscript.Arguments.Named.Exists("h") Then
      Wscript.Echo "Plugin help screen:"
      Wscript.Arguments.ShowUsage()
      Wscript.Quit(3)
End If

'*******************************************************************
' Main
'*******************************************************************
Dim objLocator
Dim objServices
Dim colItems
Dim colServiceList
Dim objExchService
Dim SumMessages
Dim intWarning
Dim intCritical
Dim objItem
Dim intResult
Dim strResult
Dim strComputer
Dim strServiceName

SumMessages = 0

strComputer = "."
strServiceName = "MSMQ"

intWarning = 100000
intCritical = 200000

On Error Resume Next
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objServices = objLocator.ConnectServer(strComputer, "Root/CimV2")

Set colServiceList = objServices.ExecQuery("Select * From Win32_Service Where Name='" & strServiceName & "'")

If (Err.Number = 0) And IsObject(colServiceList) Then
    If colServiceList.Count > 0 Then

        '
        Set colItems = objServices.ExecQuery("Select * From Win32_PerfRawData_MSMQ_MSMQQueue where MessagesInQueue > 1")
        For Each objItem in colItems
            SumMessages = SumMessages + objItem.MessagesInQueue
        Next
        If IsEmpty(SumMessages) Then
            strResult = "WARNING ALERT! Message Queue UNAVAILABLE"
            intResult = 1
        ElseIf SumMessages > intCritical Then
            strResult = "CRITICAL ALERT! Number of messages in queue: " & SumMessages
            intResult = 2
        ElseIf SumMessages > intWarning Then
            strResult = "WARNING ALERT! Number of messages in queue: " & SumMessages
            intResult = 1
        ElseIf SumMessages < intWarning Then
            strResult = "No Alert. Number of messages in queue: " & SumMessages
            intResult = 0
        End If
    Else
        strResult = "No Alert. System is not a MSMQ server."
        intResult = 0
    End If
End If

Select case intResult
  Case 0 wscript.echo strResult
         wscript.quit(0)
  Case 1 wscript.echo strResult
         wscript.quit(1)
  Case 2 wscript.echo strResult
         wscript.quit(2)
end select

VisualBasic Script check_exch_mq.wsf

PLEASE NOTE:
This script has been replaced with a PowerShell version that works with Exchange 2003 as well as Exchange 2010.
http://irl33t.com/blog/2011/08/powershell-script-watch-exchange-queues.ps1

Project Objective:
Create a Nagios addon to be run with NRPE/NSClient++ that checks the Exchange 2003 message queue for “stuck” messages.

Problem to be solved:
Increased monitoring of Exchange 2003 server. Get notified when messages are not leaving message queue.

'***********************************************************************
' "check_exch_mq.wsf"
'
' Written by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'
' If you edit please keep my name as an original author and
' keep me apprised of the changes, see email address above.
' This code may not be used for commercial purposes.
' You the executor,runner,user accept all liability.
' This code comes with ABSOLUTELY NO WARRANTY.
' You may redistribute copies of the code under the terms of the GPL v2.
' -----------------------------------------------------------------------
' 2010.09.26 ver 1.0
' Checks number of messages in Exchange message queue. If warning or
' critical thresholds are reached number of messages are outputted.
'************************************************************************

<job>
<runtime>
  <description>

check_exch_mq (nrpe_nt-plugin) 1.0
This nrpe_nt plugin come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License.

  </description>
    <named
      name="h"
      helpstring="Help"
      type="simple"
      required="false"
    />
  />

  <example>

  You do not need a string for this plugin.

 Checks number of messages in Exchange message queue. If warning or
 critical thresholds are reached number of messages are outputted.

  Usage: command [check_exch_mq]
  c:Windowssystem32cscript.exe //NoLogo //T:10 check_exch_mq.wsf

  </example>

</runtime>

<script language="VBScript">

'*******************************************************************
' Help
'*******************************************************************
If Wscript.Arguments.Named.Exists("h") Then
      Wscript.Echo "Plugin help screen:"
      Wscript.Arguments.ShowUsage()
      Wscript.Quit(3)
End If

'*******************************************************************
' Main
'*******************************************************************
Dim objLocator
Dim objServices
Dim colItems
Dim colServiceList
Dim objExchService
Dim SumMessages
Dim intWarning
Dim intCritical
Dim objItem
Dim intResult
Dim strResult
Dim strComputer
Dim strServiceName

SumMessages = 0

strComputer = "."
strServiceName = "MSExchangeSA"

intWarning = 10
intCritical = 20

On Error Resume Next
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Set objServices = objLocator.ConnectServer(strComputer, "Root/CimV2")

Set colServiceList = objServices.ExecQuery("Select * From Win32_Service Where Name='" & strServiceName & "'")

If (Err.Number = 0) And IsObject(colServiceList) Then
    If colServiceList.Count > 0 Then

        Set objExchService = objLocator.ConnectServer (strComputer, "rootcimv2ApplicationsExchange")
        Set colItems = objExchService.ExecQuery("SELECT * FROM ExchangeQueue",,48)
        For Each objItem in colItems
            SumMessages = SumMessages + objItem.NumberOfMessages
        Next
        If IsEmpty(SumMessages) Then
            strResult = "WARNING ALERT! Message Queue UNAVAILABLE"
            intResult = 1
        ElseIf SumMessages > intCritical Then
            strResult = "CRITICAL ALERT! Number of messages in queue: " & SumMessages
            intResult = 2
        ElseIf SumMessages > intWarning Then
            strResult = "WARNING ALERT! Number of messages in queue: " & SumMessages
            intResult = 1
        ElseIf SumMessages < intWarning Then
            strResult = "No Alert. Number of messages in queue: " & SumMessages
            intResult = 0
        End If
    Else
        strResult = "No Alert. System is not an Exchange server."
        intResult = 0
    End If
End If

Select case intResult
  Case 0 wscript.echo strResult
         wscript.quit(0)
  Case 1 wscript.echo strResult
         wscript.quit(1)
  Case 2 wscript.echo strResult
         wscript.quit(2)
end select

VisualBasic Script check_eventlogs.wsf

Project Objective:
Create a Nagios addon to be run with NRPE/NSClient++ that checks the Windows event logs for errors.

Problem to be solved:
Increased monitoring of Windows systems. Get notified of any and all errors as they happen opposed to after something worse happens be it hard drive failure, service offline, etc.

Suggestions:
Use existing native Nagios module – REJECED Existing module doesn’t have enough filter capability to prevent IT from being spammed with EVERY single request AND doesnt provide verbose output/what the error even is, just that there was an error.
Accepted Solution: Write our own module to use with a WSF wrapper (as was the norm on NagiosExchange) at the time.

Future Versions:
The original version of this script and another were posted on Nagios Exchange. For whatever reason they are missing now, even though they were quite popular for some time. Future versions will utilize PowerShell over VBS as many of the commands used here are native and faster in PowerShell.

'#***********************************************************************
'# "Check_EventLogs.wsf""
'#
'# "Insipred" by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'#
'#
'# If you edit please keep my name as an original author and
'# keep me apprised of the changes, see email address above.
'# This code may not be used for commercial purposes.
'# You the executor,runner,user accept all liability.
'# This code comes with ABSOLUTELY NO WARRANTY.
'# You may redistribute copies of the code under the terms of the GPL v2.
'# -----------------------------------------------------------------------
'# Notes:
'# The core of this script was re-written by two collegues of mine.
'# I was having problems with my previous attempts at solving this problem
'# So I mailed what I had off to a friend, when it came back it was re-written.
'# Thank you dstenseth and acakir, may the foos gods smile upon thee.
'# For debugging I recomend testing your queries out with wbemtest.
'# I adapted this script from ronald van vugt's Check_Services.wsf
'# -----------------------------------------------------------------------
'# 2007.07.31 ver FINAL
'#
'# Summary:
'# Checks System and Application event logs for Warnings and Errors;
'# If an error(s) are found, send verbose information including error message.
'#************************************************************************

<job>
<runtime>
  <description>

Check_EventLogs (nrpe_nt-plugin) 1.0
This nrpe_nt plugin come with ABSOLUTELY NO WARRANTY. You may redistribute
copies of the plugins under the terms of the GNU General Public License v2.

  </description>
    <named
      name="h"
      helpstring="Help"
      type="simple"
      required="false"
    />
  />

  <example>

  You do not need a string for this plugin.

  This script checks the event logs for Warnings and Errors;
  If an error is found, verbose information is sent back. A
  registry key is written in order to track when the last time
  checked was.

  Usage:
  command [check_eventlogs]=c:Windowssystem32cscript.exe //NoLogo //T:10 check_eventlogs.wsf

  </example>

</runtime>

<script language="VBScript">

'*******************************************************************
' Help
'*******************************************************************
If Wscript.Arguments.Named.Exists("h") Then
      Wscript.Echo "Plugin help screen:"
      Wscript.Arguments.ShowUsage()
      Wscript.Quit(0)
End If

'*******************************************************************
' Main
'*******************************************************************
Dim dtmFrom
Dim errCount
Dim intResultWarning
Dim intResultError
Dim strResultWarning
Dim strResultError
Dim strComputer
Dim oReg

Const AppKey = "SYSTEMCurrentControlSetServicesNRPE_NT"
Const AppVal = "LastExec"
Const CONVERT_TO_LOCAL_TIME = True
Const ForReading = 1
Const ForWriting = 2
Const HKLM = &H80000002

intResultWarning = 0
intResultError = 0
ExecDate_Current = CDate(Now)
strComputer = "."

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\" & strComputer & "rootdefault:StdRegProv")
oReg.GetStringValue HKLM,AppKey,AppVal,ExecDate_Last 

if IsNull ( ExecDate_Last ) then
        oReg.CreateKey HKLM, AppKey
        ExecDate_Last = CDate(Now)
else
        ExecDate_Last = CDate(ExecDate_Last)
end If

Set dtmFrom = CreateObject("WbemScripting.SWbemDateTime")
dtmFrom.SetVarDate ExecDate_Last, CONVERT_TO_LOCAL_TIME
Set dtmTo = CreateObject("WbemScripting.SWbemDateTime")
dtmTo.SetVarDate ExecDate_Current, CONVERT_TO_LOCAL_TIME

Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\" & strComputer & "rootcimv2")
query = "SELECT * FROM Win32_NTLogEvent WHERE (Logfile='Application' AND Type<>'Information' AND TimeWritten >='" & dtmFrom & "')_
         or (Logfile='System' AND Type<>'Information' AND TimeWritten >='" & dtmFrom & "') "

Set colEvents = objWMI.ExecQuery(query)
oReg.SetStringValue HKLM,AppKey,AppVal,CStr(Now)
errCount = colEvents.Count

if ( errCount > 0 ) then

        For Each objEvent in colEvents
                if objEvent.Type = "Error" then
                        intResultError = 2
                        if strResultError <> "" then
                                strResultError = _
                                objEvent.Logfile & " Log - Error!! " & vbCRLF &_
                                "Source: " & objEvent.SourceName & vbCRLF &_
                                "Event Code: " & objEvent.EventCode & vbCRLF &_
                                "Message: " & objEvent.Message & " " & vbCRLF &_
                                vbCRLF & strResultError
                        else
                                strResultError = _
                                objEvent.Logfile & " Log - Error!! " & vbCRLF &_
                                "Source: " & objEvent.SourceName & vbCRLF &_
                                "Event Code: " & objEvent.EventCode & vbCRLF &_
                                "Message: " & objEvent.Message & " " & vbCRLF
                        end if
                else
                        if objEvent.Type = "Warning" then
                                intResultWarning = 1
                                if strResultWarning <> "" then
                                        strResultWarning = _
                                        objEvent.Logfile & " Log - Warning! " & vbCRLF &_
                                        "Source: " & objEvent.SourceName & vbCRLF &_
                                        "Event Code: " & objEvent.EventCode & vbCRLF &_
                                        "Message: " & objEvent.Message & " " & vbCRLF &_
                                        vbCRLF & strResultWarning
                                else
                                        strResultWarning = _
                                        objEvent.Logfile & " Log - Warning! " & vbCRLF &_
                                        "Source: " & objEvent.SourceName & vbCRLF &_
                                        "Event Code: " & objEvent.EventCode & vbCRLF &_
                                        "Message: " & objEvent.Message & " " & vbCRLF
                                end if
                        end if
                end if
        next
end if

Select case intResultWarning + intResultError
  Case 0 wscript.echo "No Errors or Warnings found in System or Application Event Logs"
         wscript.quit(0)
  Case 1 wscript.echo strResultWarning
         wscript.quit(1)
  Case 2 wscript.echo strResultError
         wscript.quit(2)
  Case 3 wscript.echo strResultWarning & vbCRLF & strResultError
         wscript.quit(2)
end select

' ----- End of Script -----------------------------------------------------------------

Function WMIDateStringToDate(dtmEventDate)
    WMIDateStringToDate = CDate(Mid(dtmEventDate, 5, 2) & "/" & _
        Mid(dtmEventDate, 7, 2) & "/" & Left(dtmEventDate, 4) _
            & " " & Mid (dtmEventDate, 9, 2) & ":" & _
                Mid(dtmEventDate, 11, 2) & ":" & Mid(dtmEventDate, _
                    13, 2))
End Function
</script>
</job>

VisualBasic Script Printers-Site-Install.vbs

Project Objective:
Reduce total cost of ownership/administration time on adding/replacing printers by automatically adding them at logon.

Problem to be solved:
This script replaces my existing batch script that uses con2prt.exe. The problem with con2prt.exe is that it isn’t great at removing network printers without removing PDF writers and or local attached printers.

Future Versions:
At some point I’d like to revisit this script and build some more intelligence into site and printer selection. I’d like for it to leverage AD to determine a system’s or user’s site then install printers accordingly.

'
' Printers-Site-Install.vbs
'
' Written by Aaron Wurthmann (aaron (AT) wurthmann (DOT) com)
'
' If you edit please keep my name as an original author and
' keep me apprised of the changes, see email address above.
' This code may not be used for commercial purposes.
' You the executor, runner, user accept all liability.
' This code comes with ABSOLUTELY NO WARRANTY.
' You may redistribute copies of the code under the terms of the GPL v2.
' -----------------------------------------------------------------------
' 2007-05-02 version 2
'
' Summary:
' Reduce total cost of ownership/administration time on adding/replacing 
' printers by automatically adding them at logon.
'
' -----------------------------------------------------------------------


Dim WshShell, oExec, output
Dim fso, tmpFile
Dim strComputerName
Dim strBuff
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = CreateObject("WScript.Shell")
Set WshNetwork = CreateObject("WScript.Network")
Set objADSysInfo = CreateObject("ADSystemInfo")

' EDIT THIS SECTION WITH YOUR INFO
' If Site X then Printer X, if Site Y then Printer Y
if objADSysInfo.SiteName="San-Jose-Site" then
 strSiteServer="MyPrintServer"
end if

' END EDIT SECTION
 
' Remove Any Other (other than Site Print Server) Network Printers
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters =  objWMIService.ExecQuery ("Select * from Win32_Printer WHERE Name LIKE '%\\\\%'")
For Each objPrinter in colInstalledPrinters
 ' WScript.Echo objPrinter.Name
 tmp = InStr(1, objPrinter.Name, strSiteServer, 1)
 if tmp = 0 Then
  WshNetwork.removePrinterConnection objPrinter.Name, true, true
 end if
Next
' Enumerate Site Printer Server and Add Connections if Needed
Set oExec = WshShell.Exec("net view \\" & strSiteServer)
strBuff = oExec.StdOut.ReadAll
arrayBuff = split(strBuff, vbCrLf, -1, 1)
for each buff in arrayBuff
        result = InStr(1, buff, "Print ", 1)
        if result > 0 Then
         printerName = split(buff, " ", -1, 1)(0)
          connName = "\\" & strSiteServer & "\" & printerName
                 WshNetwork.AddWindowsPrinterConnection connName
        end if
next