SetLocale("en-us")
HandleErrorContinue("Cannot set en-us locale")
Dim WShell : Set WShell = CreateObject("wscript.shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
HandleError("CreateObject('Scripting.FileSystemObject')")
Dim programmFilesFolder : programmFilesFolder = GetProgrammFilesFolder()
HandleError("GetProgrammFilesFolder()")
Dim oAPI : Set oAPI = CreateObject("MOM.ScriptAPI")
HandleError("CreateObject(MOM.ScriptAPI)")
Dim AVIcodeInstallPath : AVIcodeInstallPath = programmFilesFolder & "\AVIcode\Intercept\SCOM2007\EnterpriseMP\"
Dim Args : Set Args = WScript.Arguments
if Args.Count < 1 then
WScript.Quit
end if
Dim Days : Days = Args(0)
Dim operator : Set operator = new LogsOperator
operator.ReadLogFiles Days
Class LogsOperator
Dim FSO
Dim ForReading
Dim ForWriting
Dim fileMutex
Private Sub Class_Initialize()
On Error Resume Next
Set FSO = CreateObject("Scripting.FileSystemObject")
ForReading = 1
ForWriting = 2
If CreateFileMutexFile() Then
CreateFileScript(AVIcodeInstallPath & "DeleteApplication.vbs")
CloseFileMutexFile()
Else
LogEvent "Cannot create DeleteApplication script file. Object Scripting Library in use.", 2
Wscript.Quit 0
End If
End Sub
Sub ReadLogFiles(Days)
On Error Resume Next
Dim logsFolderStr : logsFolderStr = AVIcodeInstallPath & "Temp\"
If FSO.FolderExists(logsFolderStr) = True Then
Dim logsFolder : Set logsFolder = FSO.GetFolder(logsFolderStr)
HandleError("Could not get folder: " & logsFolderStr)
Dim filesColl : Set filesColl = logsFolder.Files
HandleError("Could not get files from folder: " & logsFolderStr)
For Each file in filesColl
Dim fileNameStart : fileNameStart = Left(file.Name, 12)
If (fileNameStart = "Application_") OR (fileNameStart = "Transaction_") Then
Dim fullFileName : fullFileName = logsFolderStr & file.Name
Dim fil : set fil = fso.getFile(fullFileName)
HandleError("Cannot get file information: " & fullFileName)
if fil.size > 0 then
Dim content
Dim dateTime
Dim discoveryInterval
Dim Counter : Counter = 0
do
Err.Clear()
Dim textStream : Set textStream = FSO.OpenTextFile(fullFileName, ForReading, False)
HandleError("Could not open text file: " & fullFileName)
content = textStream.ReadAll()
HandleError("Could not read content from file: " & fullFileName)
If (Len(content) <= 1) OR (NOT (Err = 0)) Then
WScript.Sleep Int(300 * Rnd)
Counter = Counter+1
End If
loop While (Err <> 0) AND (Counter < 40)
If Counter < 40 Then
' good
Else
' bad
If NOT (Err = 0) Then
HandleError("Could not get UPDATE_DATE or DISCOVERY_INTERVAL from file: " & fullFileName)
Else
End If
End If
If discoveryInterval = "" Then
discoveryInterval = 86400
End If
If IsDate(dateTime) Then
Dim diff : diff = DateDiff("s", CDate(dateTime), Now())
HandleError("Err in DateDiff")
Dim secondsDiff : secondsDiff = CInt(Days) * 86400
Dim needDelete : needDelete = False
If (CLng(diff) > CLng(secondsDiff)) Then
If (CLng(diff) > CLng(discoveryInterval)) Then
If (fileNameStart = "Application_") Then
ProcessApplication content, fullFileName
Else
ProcessTransaction content, fullFileName
End If
needDelete = True
End If
End If
End If
textStream.Close()
HandleError("Failed to close the file: " & fullFileName)
If needDelete = True Then
If CreateFileMutexFile() Then
FSO.DeleteFile(fullFileName)
HandleErrorContinue("Failed to delete the file: " & fullFileName)
CloseFileMutexFile()
Else
LogEvent "Cannot delete the file: " & fullFileName & ". Object Scripting Library in use.", 2
End If
End If
End If
End If
Next
End If
End Sub
Private Function ProcessApplication(content, fileName)
On Error Resume Next
Dim displayName : displayName = GetValueForElement(content, "[DISPLAY_NAME]")
HandleError("Could not get displayName from file: " & fileName)
Dim applicationName : applicationName = GetValueForElement(content, "[APPLICATION_NAME]")
HandleError("Could not get applicationName from file: " & fileName)
Dim appType : appType = GetValueForElement(content, "[APPLICATION_TYPE]")
HandleError("Could not get applicationType from file: " & fileName)
RemoveApplication displayName, appType
HandleError("Could not delete application from monitoring: '" & displayName & "'")
End Function
Private Function ProcessTransaction(content, fileName)
On Error Resume Next
Dim displayName : displayName = GetValueForElement(content, "[DISPLAY_NAME]")
HandleError("Could not get displayName from file: " & fileName)
Dim transactionType : transactionType = GetValueForElement(content, "[TRANSACTION_TYPE]")
HandleError("Could not get transactionType from file: " & fileName)
Dim applicationType : applicationType = GetValueForElement(content, "[APPLICATION_TYPE]")
HandleError("Could not get applicationType from file: " & fileName)
Dim functionName : functionName = GetValueForElement(content, "[FUNCTION_NAME]")
HandleError("Could not get functionName from file: " & fileName)
Dim applicationDisplayName : applicationDisplayName = GetValueForElement(content, "[APPLICATION_DISPLAY_NAME]")
HandleError("Could not get applicationDisplayName from file: " & fileName)
Dim applicationName : applicationName = GetValueForElement(content, "[APPLICATION_NAME]")
HandleError("Could not get applicationName from file: " & fileName)
Dim pageName, methodName
If transactionType = "WebTransaction" Then
pageName = GetValueForElement(content, "[PAGE_NAME]")
HandleError("Could not get pageName from file: " & fileName)
End If
If transactionType = "WebServiceTransaction" Then
pageName = GetValueForElement(content, "[PAGE_NAME]")
HandleError("Could not get pageName from file: " & fileName)
methodName = GetValueForElement(content, "[METHOD_NAME]")
HandleError("Could not get methodName from file: " & fileName)
End If
RemoveTransactionFromMonitoring applicationDisplayName, applicationType, displayName, functionName, pageName, methodName
HandleError("Cannot delete transaction from monitoring.")
End Function
Private Function GetValueForElement(content, elementName)
On Error Resume Next
GetValueForElement = ""
Dim startElementName : startElementName = 0
startElementName = InStr(1, content, elementName, 1)
If (startElementName > 0) Then
startElementName = startElementName + Len(elementName)
Dim endElementName : endElementName = InStr(startElementName, content, vbcrlf, 1)
if(endElementName > 0) Then
GetValueForElement = Trim(Mid (content, startElementName, endElementName - startElementName))
End If
Else
Err.Raise 20000, "AVIcode .NET Enterprise Management Pack for OpsMgr 2007", "Application log parsing. Cannot found element '" & elementName & "' in " & content, 0, 0
End If
End Function
Private Function GetValueForElementOptinal(content, elementName)
On Error Resume Next
GetValueForElementOptinal = ""
Dim startElementName : startElementName = 0
startElementName = InStr(1, content, elementName, 1)
If (startElementName > 0) Then
startElementName = startElementName + Len(elementName)
Dim endElementName : endElementName = InStr(startElementName, content, vbcrlf, 1)
if(endElementName > 0) Then
GetValueForElementOptinal = Trim(Mid (content, startElementName, endElementName - startElementName))
End If
End If
End Function
Private Function CorrectObjectName(nameStr)
On Error Resume Next
Private Function RemoveApplication(DisplayName, AppType)
On Error Resume Next
RemoveApplication = ""
Dim sPath : sPath = """" & AVIcodeInstallPath & "DeleteApplication.vbs"" """ & DisplayName & """ """ & AppType & """"
Dim sPathClient : sPathClient = """" & AVIcodeInstallPath & "DeleteClientApplication.vbs"" """ & DisplayName & """"
If CreateFileMutexFile() Then
'remove from client monitring
RemoveApplication = RunScriptx86(sPathClient)
'remove from server monitring
RemoveApplication = RunScriptx86(sPath)
CloseFileMutexFile()
If LCase(AppType) = "webapplication" Then
RecycleIISAlert "Application", DisplayName
End If
Else
LogEvent "Cannot remove application '" & DisplayName & ". Object Scripting Library in use.", 2
Wscript.Quit 0
End If
End Function
Sub RemoveTransactionFromMonitoring(ApplicationName, ApplicationType, InstanceName, FunctionName, PageName, MethodName)
On Error Resume Next
If CreateFileMutexFile() Then
Dim Executor : Set Executor = CreateObject("Agent.StatisticCountersScriptingLibrary.CExecutor")
HandleError("Cannot create 'Agent.StatisticCountersScriptingLibrary.CExecutor' object.")
Dim Properties : Set Properties = CreateObject("Agent.StatisticCountersScriptingLibrary.CProperties")
HandleError("Cannot create 'Agent.StatisticCountersScriptingLibrary.CProperties' object.")
Executor.Init Properties
HandleError("'Agent.StatisticCountersScriptingLibrary.CExecutor' cannot be initialized")
Executor.Execute "Open", Properties
HandleError("'Agent.StatisticCountersScriptingLibrary.CExecutor' cannot open configuration file")
If NOT IsNull(PageName) and NOT IsEmpty(PageName) Then
Dim Conditions :Set Conditions = CreateObject("Agent.StatisticCountersScriptingLibrary.CProperties")
HandleError("Cannot create 'Agent.StatisticCountersScriptingLibrary.CProperties' object.")
Dim Expr : Set Expr = CreateObject("Agent.StatisticCountersScriptingLibrary.CProperties")
HandleError("Cannot create 'Agent.StatisticCountersScriptingLibrary.CProperties' object.")
If NOT IsNull(MethodName) and NOT IsEmpty(MethodName) Then
Dim Expr1 : Set Expr1 = CreateObject("Agent.StatisticCountersScriptingLibrary.CProperties")
HandleError("Cannot create 'Agent.StatisticCountersScriptingLibrary.CProperties' object.")
Expr1("key") = "SOAPAction"
Expr1("value") = MethodName
Conditions("expressions1") = Expr1
End If
Executor.Execute "GetCustomActionParameters", Properties
If NOT (Err = 0) Then
Err.Clear()
Else
Executor.Execute "RemoveCustomAction", Properties
HandleError("Cannot execute RemoveCustomAction command in SCScriptingLibrary.")
Executor.Execute "Save", Properties
HandleError("Cannot execute Save command.")
If LCase(ApplicationType) = "webapplication" Then
RecycleIISAlert "Transaction", InstanceName
End If
End If
CloseFileMutexFile()
Else
LogEvent "Cannot delete transaction" & InstanceName & " from monitoring. Object Statistic Library in use.", 2
Wscript.Quit 0
End If
End Sub
Function RecycleIISAlert(ObjType, Name)
On Error Resume Next
Dim message : message = ObjType & " '" & Name & "' was successfully removed from monitoring." & vbcrlf _
& "Changes in the settings will only take effect after recycling the IIS."
Call oAPI.LogScriptEvent("AVIcode .NET Enterprise Management Pack for OpsMgr 2007", 19996, 0, message)
End Function
Function CreateFileMutexFile()
On Error Resume Next
Dim fileName : fileName = AVIcodeInstallPath & "StatisticMutex.tmp"
Dim Counter : Counter = 0
do
Err.Clear()
Set fileMutex = fso.OpenTextFile(FileName, 2 , True)
If NOT (Err = 0) Then
WScript.Sleep Int(300 * Rnd)
Counter = Counter+1
End If
loop While (Err <> 0) AND (Counter < 100)
If Counter < 100 Then
CreateFileMutexFile = True
Else
CreateFileMutexFile = False
End If
End Function
Function CloseFileMutexFile()
On Error Resume Next
if NOT(isEmpty(fileMutex)) AND NOT(isNull(fileMutex)) Then
fileMutex.Close()
If NOT (Err = 0) Then
Err.Clear()
End If
End If
End Function
Private Function RunScriptx86(scriptName)
Dim WinDir : WinDir = wshell.ExpandEnvironmentStrings("%windir%")
Dim cScriptFileName : cScriptFileName = WinDir & "\SysWOW64\cscript.exe"
If NOT FSO.FileExists(cScriptFileName) Then
cScriptFileName = WinDir & "\System32\cscript.exe"
End If
Dim oExec
Set oExec = WShell.Exec(cScriptFileName & " " & scriptName)
HandleError("Cannot start process '" & cScriptFileName & " " & scriptName & "'")
Dim scriptOutput : scriptOutput = ""
Do While oExec.Status = 0
WScript.Sleep 100
Loop
If Not oExec.StdOut.AtEndOfStream Then
'for exclude cscript.exe header
oExec.StdOut.ReadLine()
oExec.StdOut.ReadLine()
oExec.StdOut.ReadLine()
if (oExec.ExitCode = 0) Then
scriptOutput = Trim(scriptOutput & oExec.StdOut.ReadLine())
Else
scriptOutput = Trim(scriptOutput & oExec.StdOut.ReadAll())
LogEvent "Script Failed: " & cScriptFileName & " " & scriptName & "; OutPut:" & scriptOutput, 1
Wscript.Quit 0
End if
End If
RunScriptx86 = scriptOutput
End Function
Private Function CreateFileScript(filePath)
Dim f
wshell.CurrentDirectory = AVIcodeInstallPath
set f = FSO.OpenTextFile("DeleteApplication.vbs", 2, True )
f.WriteLine("On Error Resume Next")
f.WriteLine("")
f.WriteLine("SetLocale(""en-us"")")
f.WriteLine("HandleErrorContinue(""Cannot set en-us locale"")")
f.WriteLine("")
f.WriteLine("Dim Args : Set Args = WScript.Arguments")
f.WriteLine("if Args.Count < 2 then")
f.WriteLine(" WScript.Quit ")
f.WriteLine("end if")
f.WriteLine("Dim applicationName : applicationName = Args(0)")
f.WriteLine("Dim applicationType : applicationType = Args(1)")
f.WriteLine("")
f.WriteLine("Dim Executor : Set Executor = CreateObject(""InterceptScripting.Executor"")")
f.WriteLine("HandleError(""Cannot create'InterceptScripting.Executor' object."")")
f.WriteLine("")
f.WriteLine("Executor.Init nothing")
f.WriteLine("HandleError(""Cannot initialize 'InterceptScripting.Executor' object."")")
f.WriteLine(" ")
f.WriteLine("Dim Properties : Set Properties = Executor.CreateProperties")
f.WriteLine("HandleError(""Error after 'Properties = Executor.CreateProperties'"")")
f.WriteLine("")
f.WriteLine("Properties(""host"") = applicationType")
f.WriteLine("Properties(""name"") = applicationName")
f.WriteLine("Properties(""monitor"") = ""PMonitor""")
f.WriteLine("")
f.WriteLine("Dim Application : Set Application = Executor.Execute(""GetApplicationParameters"", Properties)")
f.WriteLine("If Err <> 0 Then")
f.WriteLine(" Err.Clear()")
f.WriteLine("Else")
f.WriteLine(" Executor.Execute ""RemoveApplication"", Properties")
f.WriteLine(" HandleError(""Error after 'Executor.RemoveApplication'"") ")
f.WriteLine("")
f.WriteLine(" Executor.Execute ""Save"", Properties")
f.WriteLine(" HandleError(""Error after 'Executor.Save'"") ")
f.WriteLine("End If")
f.WriteLine("")
f.WriteLine("Sub HandleError(customMessage)")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" LogError customMessage")
f.WriteLine(" Wscript.Quit 1")
f.WriteLine(" End If ")
f.WriteLine("End Sub")
f.WriteLine("")
f.WriteLine("Function HandleErrorContinue(customMessage)")
f.WriteLine(" HandleErrorContinue = False")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" LogError customMessage")
f.WriteLine(" Err.Clear")
f.WriteLine(" HandleErrorContinue = True")
f.WriteLine(" End If")
f.WriteLine("End Function")
f.WriteLine("")
f.WriteLine("Sub LogError(customMessage)")
f.WriteLine(" Dim msg")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" msg = Replace("" Error: #P1# Description: #P2# "", ""#P1#"", CStr(Err.number) )")
f.WriteLine(" msg = Replace(msg, ""#P2#"", Err.Description )")
f.WriteLine(" msg = customMessage & VbCrLf & msg & VbCrLf")
f.WriteLine(" WScript.StdOut.WriteLine msg ")
f.WriteLine(" End If")
f.WriteLine("End Sub")
f.close
set f = FSO.OpenTextFile("DeleteClientApplication.vbs", 2, True )
f.WriteLine("On Error Resume Next")
f.WriteLine("")
f.WriteLine("SetLocale(""en-us"")")
f.WriteLine("HandleErrorContinue(""Cannot set en-us locale"")")
f.WriteLine("")
f.WriteLine("Dim Args : Set Args = WScript.Arguments")
f.WriteLine("if Args.Count < 1 then")
f.WriteLine(" WScript.Quit")
f.WriteLine("end if")
f.WriteLine("")
f.WriteLine("Dim applicationName : applicationName = Args(0)")
f.WriteLine("")
f.WriteLine("DisableApplicationMonitoring applicationName")
f.WriteLine("")
f.WriteLine("Function DisableApplicationMonitoring(applicationName)")
f.WriteLine(" On Error Resume Next")
f.WriteLine(" ")
f.WriteLine(" Dim Executor : set Executor = CreateObject(""Agent.CSMScripting.CExecutor"")")
f.WriteLine(" HandleError(""Cannot create Agent.CSMScripting.CExecutor object"")")
f.WriteLine(" Executor.Init """"")
f.WriteLine(" HandleError(""Cannot initialize Agent.CSMScripting.CExecutor object"")")
f.WriteLine(" ")
f.WriteLine(" Dim ApplicationProperties : set ApplicationProperties = CreateObject(""Agent.CSMScripting.Common.CProperties"")")
f.WriteLine(" HandleError(""Cannot create Agent.CSMScripting.Common.CProperties"")")
f.WriteLine(" ApplicationProperties(""applicationType"") = ""webApplication""")
f.WriteLine(" ApplicationProperties(""displayName"") = applicationName")
f.WriteLine(" ")
f.WriteLine(" Executor.Execute ""GetApplicationParameters"", ApplicationProperties")
f.WriteLine(" ")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" Err.Clear")
f.WriteLine(" Wscript.Quit 0")
f.WriteLine(" End If ")
f.WriteLine(" ")
f.WriteLine(" Executor.Execute ""RemoveApplication"", ApplicationProperties")
f.WriteLine(" HandleError(""Cannot delete uX application. Application name: "" & applicationName)")
f.WriteLine(" ")
f.WriteLine(" Executor.Execute ""Save"", ResultProperties")
f.WriteLine(" HandleError(""Cannot save changes after deletion of uX application "" & applicationName)")
f.WriteLine(" ")
f.WriteLine("End Function")
f.WriteLine("")
f.WriteLine("")
f.WriteLine("Sub HandleError(customMessage)")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" LogError customMessage")
f.WriteLine(" Wscript.Quit 1")
f.WriteLine(" End If ")
f.WriteLine("End Sub")
f.WriteLine("")
f.WriteLine("Function HandleErrorContinue(customMessage)")
f.WriteLine(" HandleErrorContinue = False")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" LogError customMessage")
f.WriteLine(" Err.Clear")
f.WriteLine(" HandleErrorContinue = True")
f.WriteLine(" End If")
f.WriteLine("End Function")
f.WriteLine("")
f.WriteLine("Sub LogError(customMessage)")
f.WriteLine(" Dim msg")
f.WriteLine(" If Not (Err.number = 0) Then")
f.WriteLine(" msg = Replace("" Error: #P1# Description: #P2# "", ""#P1#"", CStr(Err.number) )")
f.WriteLine(" msg = Replace(msg, ""#P2#"", Err.Description )")
f.WriteLine(" msg = customMessage & VbCrLf & msg & VbCrLf")
f.WriteLine(" WScript.StdOut.WriteLine msg ")
f.WriteLine(" End If")
f.WriteLine("End Sub")
f.close
End Function
End Class
Function GetProgrammFilesFolder()
GetProgrammFilesFolder = wshell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
if GetProgrammFilesFolder = "%ProgramFiles(x86)%" Then
GetProgrammFilesFolder = wshell.ExpandEnvironmentStrings("%ProgramFiles%")
End If
End Function
Sub HandleError(customMessage)
If Not (Err.number = 0) Then
LogError customMessage
Wscript.Quit 0
End If
End Sub
Function HandleErrorContinue(customMessage)
HandleErrorContinue = False
If Not (Err.number = 0) Then
LogError customMessage
Err.Clear
HandleErrorContinue = True
End If
End Function
Sub LogError(customMessage)
Dim msg
If Not (Err.number = 0) Then
msg = Replace(" Error: #P1# Description: #P2# ", "#P1#", CStr(Err.number) )
msg = Replace(msg, "#P2#", Err.Description )
msg = customMessage & VbCrLf & msg & VbCrLf
If UCase(Hex(Err.number)) = UCase("80041006") Then
msg = msg & "WMI Error. Not enough memory for the operation." & VbCrLf
End If
WScript.StdOut.WriteLine msg
msg = msg & " [" & ScriptInfo() & "]"
LogEvent msg, 1
End If
End Sub
Function ScriptInfo()
Dim commandLineInfo : commandLineInfo = WScript.ScriptFullName
Dim argument
For Each argument In WScript.Arguments
commandLineInfo = commandLineInfo & " """ & argument & """"
Next
ScriptInfo = commandLineInfo
End Function
Sub LogEvent (message, eventType)
Dim errorEventId : errorEventId = 20000
Dim oAPI0 : Set oAPI0 = CreateObject("MOM.ScriptAPI")
Call oAPI0.LogScriptEvent("AVIcode .NET Enterprise Management Pack for OpsMgr 2007", errorEventId, eventType, message)
End Sub </Script></ScriptBody>
<TimeoutSeconds>600</TimeoutSeconds>
</WriteAction>
</MemberModules>
<Composition>
<Node ID="DeleteWA"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.BaseData</OutputType>
<InputType>System!System.BaseData</InputType>
</WriteActionModuleType>