Sei sulla pagina 1di 12

Option Explicit '========================================================================== ' ' VBScript Source File -- Created with SAPIEN Technologies PrimalScript 4.

1 ' ' Name : CominedEventLogReportsScript.vbs ' ' AUTHOR: Microsoft , Microsoft ' DATE : 5/28/2011 ' ' USAGE : cscript DiskCleanup.vbs ' ' Where MinutesCount is the number of minutes. The script will ' report the filtered events for last minutes mentioned he re. ' ' COMMENT: This script is intended Cleaning up the Disk and if running low Disk Dim OldLog, OldProfile, warning, critical Dim MailTo, MailCC, MailFrom, SMTPServer, SMTPPort Dim dictArgs, CustomizedCleanupFile OldLog = 365 'Specify how many days old logs to be deleted OldProfile = 7 'specify how many days old profiles to be removed Warning = 50 Critical = 5 MailTo = "nagamani.jayabalan@hp.com" MailCC = "nagamani.jayabalan@hp.com" MailFrom = "monitoring@con-way.com" SMTPServer = "mailhost.con-way.com" SMTPPort = 25 CustomizedCleanupFile = "c:\disk\applicationlog.txt" ' '==========================================================================

'========================================================================== ' ' START Global Variable Decleration ' '========================================================================== Public Const RECYCLE_BIN = &Ha& Public Const FILE_SIZE = 3 Public Const HARD_DISK = 3 Public Const ADS_SCOPE_SUBTREE = 2 Public Const E_ADS_PROPERTY_NOT_FOUND = &h8000500D Public Const ADS_PROPERTY_APPEND = 3 Public Const HKEY_CURRENT_USER = &H80000001 ' ' iomode arguements ' Public Const FORREAD = 1 Public Const FORWRITE = 2 Public Const FORAPPEND = 8 ' ' create arguements ' Public Const CREATE = True Public Const DONOTCREATE = False '

' format arguements ' Public Const FORMATASCII = 0 Public Const FORMATUNICODE = -1 Public Const FORMATDEFAULTSYSTEM = 1 ' ' Force Action Arguments ' Public Const FORCE = True Public Const NOFORCE = False ' ' True/False as Yes/No ' Public Const YES = True Public Const NO = False ' ' Create File System Object ' Dim objFSO Set objFSO = CreateObject("Scripting.FileSystemObject") ' ' Create Shell Object ' Dim objShell, objExecObject, strCommand Set objShell = CreateObject("WScript.Shell") 'strCommand = "%comspec% /c hostname" 'Set objExecObject = objShell.Exec(strCommand) 'ComputerName = objExecObject.StdOut.ReadAll() 'ComputerName = Left(UCase(ComputerName),Len(ComputerName)-1) ' ' Create Network Object ' Dim WshNetwork, Computername Set WshNetwork = CreateObject("WScript.Network") Computername = WshNetwork.ComputerName '========================================================================== ' ' End Global Variable Decleration ' '==========================================================================

'========================================================================== ' ' START Script Specific Variable Decleration '

'========================================================================== Dim DiskFreePercent,SystemDrive,SystemRoot,UsersProfile, ProfilePath, TempFilesP ath, TemporaryInternetFilesPath Dim StartFree, EndFree, CurrentFree Dim MailSubject, MailBody '========================================================================== ' ' END Script Specific Variable Decleration ' '==========================================================================

'/ START SCRIPT BLOCK If objFSO.FileExists("DiskCleanup.log") Then objFSO.DeleteFile("DiskCleanup.log" ) writeLog("Information: Script Execution Started") If CustomizedCleanupFile <> "" Then Call ProcessCustomizedCleanupFile(CustomizedCleanupFile) End If If DiskCleanupNeeded = True Then Dim EndFreePercent StartFree = CurrentFree Call GetOperatingSystem writeLog("Information: Starting Call LogCleanup writeLog("Information: Starting Call MemoryDumpCleanup writeLog("Information: Starting nup") Call ProfileCleanup writeLog("Information: Starting Call TempFileCleanup writeLog("Information: Starting Call TempInternetFilesCleanup writeLog("Information: Starting Call RecycleBin

" & OldLog & " days old Log Cleanup") MemoryDump Cleanup") " & OldProfile & " days old profile Clea Temporary Files Cleanup") Temporary Internet Files Cleanup") Recycle Bin cleanup")

EndFreePercent = CheckDiskSpace() EndFree = CurrentFree Call writeLog("Information: " & EndFree - StartFree & "GB of space is cl eared. Now disk is " & EndFreePercent & "% free.") MailSubject = UCase(Computername) & ": Disk Cleanup Performed" MailBody = "Disk space available before initiating cleanup " & StartFree & "GB." & VbCrLf MailBody = MailBody & "Disk space available after completion of cleanup " & EndFree & "GB." & VbCrLf MailBody = MailBody & "Disk space Cleaned by script " & EndFree - StartF ree & "GB." & VbCrLf MailBody = MailBody & "Disk space Percent free now is " & EndFreePercen t & "%" & VbCrLf wscript.Echo MailBody writeLog (MailBody) 'Call Sendmail End If

'/ END SCRIPT BLOCK

'========================================================================== ' ' START FUNCTION DECLERATIONS ' '========================================================================== Function Function1 End Function Function DiskCleanupNeeded Dim DiskUsageThreshold 'DiskUsageThreshold = CheckCleanupThreshold() DiskUsageThreshold = Warning writeLog("Information: DiskUsageThreshold is " & DiskUsageThreshold & " Percent") DiskFreePercent = CheckDiskSpace() writeLog("Information: DiskFreePercentage is " & DiskFreePercent & " Per cent") If (CInt(DiskUsageThreshold)+5) > CInt(DiskFreePercent) Then writeLog("Information: Server " & Computername & " is running at low disk space") DiskCleanupNeeded = True Else writeLog("Information: Server has sufffient space available no c leanup needed") DiskCleanupNeeded = False End If 'sDiskCleanupNeeded = True End Function Function CheckCleanupThreshold Dim df_mon, threshold, f_threshold f_threshold = False If objFSO.FileExists("C:\osit\etc\df_mon.cfg") Then writeLog("Success: df_mon.cfg file is found") Set df_mon = objFSO.OpenTextFile("c:\osit\etc\df_mon.cfg",FORREA D) If Err.Number <> 0 Then writeLog("Error: unable to open the file df_mon.cfg. Err or " & Err.Number & " occured(" & Err.Description) writeLog("Error: Script will exit now") WScript.Quit(1) Else

writeLog("Success: df_mon.cfg file opened successfully. Now reading the file") Err.Clear End If Do Until df_mon.AtEndOfStream Dim strLine, arrline strLine = ucase(df_mon.ReadLine) If Not Left(strLine,1) = "#" Then If strLine = "[NT_BASIC]" Then strLine = UCase(df_mon.ReadLine) strLine = ReadDF_MON(strLine) Do until Left(strLine,1) = "#" arrline = Split(strLine," ") 'wscript.echo ("Check" & strline & "Check") If arrline(1) = "WARNING" Then threshold = CInt(arrline (2)) f_threshold = True Exit Do Else strLine = UCase(df_mon.R eadLine) strLine = ReadDF_MON(str Line) End If Loop End If End If Loop df_mon.Close Set df_mon = Nothing If f_threshold = True Then writeLog("Success: Warning threshold value retrived from df_mon.cfg") CheckCleanupThreshold = threshold Else writeLog("Error: Warning threshold is not set in df_mon. cfg") writeLog("Error: Script will exit now") WScript.Quit(1) End If Else writeLog("Error: c:\osit\etc\df_mon.cfg file not found") writeLog("Error: Script will exit now") WScript.Quit(1) End If End Function Function ReadDF_MON(strText) strText = Replace(Replace(Replace(Replace(Replace(Replace(strText,vbTab, " ")," "," ")," "," ")," "," ")," "," ")," "," ") ReadDF_MON = strText End Function Function CheckDiskSpace Dim spaceavailable, objWMIService, colDisks, objDisk, objEnv Set objEnv = objShell.Environment("PROCESS") writeLog("Information: Checking the Disk Space Free") spaceavailable = 150

Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\.\root\cimv2") Set colDisks = objWMIService.ExecQuery _ ("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "") 'wscript.echo spaceavailable For Each objDisk in colDisks If UCase(objDisk.DeviceID) = UCase(objEnv("systemdrive")) Then spaceavailable = Round((objDisk.FreeSpace * 100)/objDisk.Size) CurrentFree = Round(objDisk.FreeSpace/(1024*1024*1024),2) 'WScript.Echo CurrentFree End If Next If spaceavailable > 100 Then writeLog("Error: Unable to get space on System Drive") writeLog("Error: Script will exit now") WScript.Quit(1) Else writeLog("Success: Retrived the space available on System Drive" ) CheckDiskSpace = spaceavailable End If End Function Function getStrFileSystemDate(ObjStr,strType) Dim objTemp getStrFileSystemDate = Null If UCase(strType) = "FOLDER" Then Set objTemp = objFSO.GetFolder(ObjStr) getStrFileSystemDate = objTemp.DateLastModified Set objTemp = Nothing ElseIf UCase(strType) = "FILE" Then Set objTemp = objFSO.GetFile(ObjStr) getStrFileSystemDate = objTemp.DateLastModified Set objTemp = Nothing End If End Function Function CheckCustomizedCleanupFile(strFile) Dim objFile1 CheckCustomizedCleanupFile = True If Not objFSO.FileExists(strFile) Then CheckCustomizedCleanupFile = False Else Set objFile1 = objFSO.OpenTextFile(strFile) Do Until objFile1.AtEndOfStream Dim strLine1,arrLine1 strLine1 = objFile1.ReadLine arrLine1 = Split(strLine1,",") If UBound(arrLine1) <> 2 Then CheckCustomizedCleanupFile = False Loop objFile1.Close Set objFile1 = Nothing End If End Function

'========================================================================== ' ' END FUNCTION DECLERATIONS ' '==========================================================================

'========================================================================== ' ' START SUB-ROUTINE DECLERATIONS ' '========================================================================== '************************************ ' Purpose1 '************************************ Sub Sub1 End Sub Sub LogCleanup Dim ProcessCommand, objExecProcessCommand, strFile, objDictOldLogs, i Set objDictOldLogs = CreateObject("Scripting.Dictionary") ProcessCommand = "%comspec% /c dir /b /s /a-d " & SystemRoot & "\*.log" Set objExecProcessCommand = objShell.Exec(ProcessCommand) writeLog("Information: Extracting the list of Old Logs") i = 0 Do Until objExecProcessCommand.StdOut.AtEndOfStream On Error Resume Next strFile = objExecProcessCommand.StdOut.Readline If Ucase(Right(strFile,3)) = "LOG" Then If (Abs(Datediff("d",Date,Cdate(getStrFileSystemDate(strFile,"FI LE")))) > OldLog) Then i = i + 1 objDictOldLogs.Add i,strFile End If End If Loop Set objExecProcessCommand = Nothing

writeLog("Information: Old Logs Deletion started") For Each i In objDictOldLogs.Items writeLog(i) 'DeleteFile(i) Next Set objDictOldLogs = Nothing End Sub Sub MemoryDumpCleanup If objFSO.FileExists(SystemRoot & "\Memory.dmp") Then writeLog("Information: Deleting Memory Dump") writeLog(SystemRoot & "\Memory.dmp") 'DeleteFile(SystemRoot & "\Memory.dmp") End If End Sub Sub ProfileCleanup Dim ProcessCommand, objExecProcessCommand 'wscript.echo "In Profile Cleanup" writeLog("Information: Starting the deletion of " & OldProfile & " days old profiles.") ProcessCommand = "%comspec% /c delprof /q /i /d:" & OldProfile 'Set objExecProcessCommand = objShell.Exec(ProcessCommand) 'do until objexecprocesscommand.stdout.atendofstream ' writeLog(objexecprocesscommand.stdout.readline) 'loop End Sub Sub TempInternetFilesCleanup Dim ProcessCommand, objExecProcessCommand, strFile, objDictOldProfiles, i Set objDictOldProfiles = CreateObject("Scripting.Dictionary") ProcessCommand = "%comspec% /c dir /b /ad " & UsersProfile Set objExecProcessCommand = objShell.Exec(ProcessCommand) writeLog("Information: Starting cleanup for Temporary internet Files") i = 0 Do Until objExecProcessCommand.StdOut.AtEndOfStream On Error Resume Next strFile = objExecProcessCommand.StdOut.Readline If (Ucase(strFile) <> ".") And (Ucase(strFile) <> "..") And (Uca se(strFile) <> "") Then If (Ucase(strFile) <> "ADMINISTRATOR") And (Ucase(strFile) <> "A LL USERS") And (Ucase(strFile) <> "CTX_STREAMINGSVC") And (Ucase(strFile) <> "DE FAULT") And (Ucase(strFile) <> "DEFAULT USER") And (Ucase(strFile) <> "PUBLIC") Then Dim ProcessCommand2, objExecProcessCommand2, temp writeLog("Delete: Deleting all contents of " & UsersProf ile & "\" & strFile & TemporaryInternetFilesPath) Call DeleteTemp(UsersProfile & "\" & strFile & Temporary InternetFilesPath) End If End If Loop End Sub Sub RecycleBin Dim ProcessCommand, objExecProcessCommand writeLog("Information: Starting cleanup of RecycleBin") ProcessCommand = "%comspec% /c for /f %%q in (`dir /b /a:s " & SystemDri

ve & "\Recycler`) do (rd /s " & SystemDrive & "\Recycler\%q)" 'Set objExecProcessCommand = objShell.Exec(ProcessCommand) ProcessCommand = "%comspec% /c DEL /f /s /q C:\RECYCLER\*.*" 'Set objExecProcessCommand = objShell.Exec(ProcessCommand) ProcessCommand = "%comspec% /c rd c:\RECYCLER /s /q" 'Set objExecProcessCommand = objShell.Exec(ProcessCommand) writeLog("Information: Completed cleanup of RecycleBin") End Sub Sub writeLog(strText) Dim logfile Set logfile = objFSO.OpenTextFile("DiskCleanup.log",FORAPPEND,CREATE) logfile.WriteLine(Now & vbTab & strText) logfile.Close Set logfile = Nothing End Sub Sub DeleteFile(strFile) Err.Clear On Error Resume Next 'objFSO.DeleteFile strFile,YES If Err.Number <> 0 Then writeLog("Delete Failed: " & strFile) Err.Clear Else writeLog("Delete Success: " & strFile) End If End Sub Sub DeleteFolder(strFolder) Err.Clear On Error Resume Next 'objFSO.DeleteFolder strFolder,YES If Err.Number <> 0 Then writeLog("Delete Failed: " & strFolder) Err.Clear Else writeLog("Delete Success: " & strFolder) End If End Sub Sub GetOperatingSystem Dim strComputer, objWMIService, colOperatingSystems, objOperatingSystem, Version, objEnv, UserName Dim oReg, strKeyPath, strValueName, IFPath Set objEnv = objShell.Environment("PROCESS") SystemDrive = objEnv("systemdrive") SystemRoot = objEnv("systemroot") ProfilePath = objEnv("userprofile") UserName = objEnv("username") strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2 ") Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem") For Each objOperatingSystem In colOperatingSystems If Left(objOperatingSystem.Version,1) = 6 Then

UsersProfile = SystemDrive & "\Users" TempFilesPath = "\AppData\Local\Temp" ElseIf Left(objOperatingSystem.Version,1) = 5 Then UsersProfile = SystemDrive & "\Documents and Settings" TempFilesPath = "\Local Settings\Temp" End If Next 'TempFilesPath = Right(objFSO.GetSpecialFolder(2).Path,Len(objFSO.GetSpe cialFolder(2).Path) - Len(ProfilePath)) 'WScript.Echo TempFilesPath Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\d efault:StdRegProv") strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell F olders" strValueName = "Cache" oReg.GetStringValue HKEY_CURRENT_USER,strKeyPath,strValueName,IFPath TemporaryInternetFilesPath = Right(IFPath,Len(IFPath)-Len(ProfilePath)) 'WScript.Echo TemporaryInternetFilesPath End Sub Sub Sendmail Dim objEmail, objTempfile Set objEmail = CreateObject("CDO.Message") objEmail.From = MailFrom objEmail.To = MailTo objEmail.CC = MailCC objEmail.Subject = MailSubject objEmail.TextBody = MailBody objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/con figuration/sendusing") = 2 objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/con figuration/smtpserver") = SMTPServer objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/con figuration/smtpserverport") = SMTPPort objEmail.Configuration.Fields.Update If objFSO.FileExists("DiskCleanup.log") Then Set objTempfile = objFSO.GetFile("DiskCleanup.log") objEmail.AddAttachment objTempfile.Path objEmail.Configuration.Fields.Update End If objEmail.Send End Sub Sub ProcessCustomizedCleanupFile(strFile) If CheckCustomizedCleanupFile(strFile) = True Then Dim objfile1, objFolder1 Set objfile1 = objFSO.OpenTextFile(strFile) Do Until objfile1.AtEndOfStream Dim strLine1, arrline1, Folder, Extension, strDays strLine1 = Trim(objfile1.ReadLine) arrline1 = Split(strLine1,",") Folder = arrline1(0) Extension = arrline1(1) strDays = CInt(arrline1(2)) If Err.Number <> 0 Then strDays = 365 Err.Clear If Not objFSO.FolderExists(Folder) Then

writeLog(Folder & " not found.") Else Dim subFile, objsubFile writeLog("Cleaning up " & strDays & " days old * ." & Extension & " files from " & Folder) Set objFolder1 = objFSO.GetFolder(Folder) For Each subFile In objFolder1.Files If Right(UCase(subFile.Path),Len(Extensi on)) = UCase(Extension) Then If (Abs(Datediff("d",Date,Cdate( getStrFileSystemDate(subFile.Path,"FILE")))) > strDays) Then writeLog(subFile.Path) 'subFile.Delete End If End If Next End If Loop objfile1.Close Else writeLog("Please verify the File " & strFile & " exists and is i n correct format (Folder,File Extension,Number of days." _ & " Where Folder is the folder where the files to be del eted are saved. File Extension the is file type to be removed." _ & " And the Number of days specifies that file should be how many days old to be removed.") End If End Sub Sub TempFileCleanup Dim ProcessCommand, objExecProcessCommand, strFile, objDictOldProfiles, i Set objDictOldProfiles = CreateObject("Scripting.Dictionary") ProcessCommand = "%comspec% /c dir /b /ad " & UsersProfile Set objExecProcessCommand = objShell.Exec(ProcessCommand) writeLog("Information: Starting Temp files cleanup") i = 0 Do Until objExecProcessCommand.StdOut.AtEndOfStream On Error Resume Next strFile = objExecProcessCommand.StdOut.Readline If (Ucase(strFile) <> ".") And (Ucase(strFile) <> "..") And (Uca se(strFile) <> "") Then If (Ucase(strFile) <> "ADMINISTRATOR") And (Ucase(strFile) <> "A LL USERS") And (Ucase(strFile) <> "CTX_STREAMINGSVC") And (Ucase(strFile) <> "DE FAULT") And (Ucase(strFile) <> "DEFAULT USER") And (Ucase(strFile) <> "PUBLIC") Then Dim ProcessCommand2, objExecProcessCommand2, temp writeLog("Delete: Deleting all contents of " & UsersProf ile & "\" & strFile & TempFilesPath) Call DeleteTemp(UsersProfile & "\" & strFile & TempFiles Path) End If End If Loop Set objExecProcessCommand = Nothing If objFSO.FolderExists(SystemRoot & "\temp") Then writeLog("Delete: Deleting all contents of " & SystemRoot & "\te mp")

Call DeleteTemp(SystemRoot & "\temp") End If If objFSO.FolderExists(SystemDrive & "\temp") Then writeLog("Delete: Deleting all contents of " & SystemDrive & "\t emp") Call DeleteTemp(SystemDrive & "\temp") End If writeLog("Information: Completed Temp files cleanup") End Sub Sub DeleteTemp (strTempPath) On Error Resume Next Dim objFolder,objDir Dim objFile Dim i writeLog(strTempPath) Set objFolder=objFSO.GetFolder(strTempPath) 'delete all files For Each objFile In objFolder.Files writeLog(objFile.Path) 'objFile.delete True Next 'delete all subfolders For i=0 To 10 For Each objDir In objFolder.SubFolders writeLog(objDir.Path) 'objDir.Delete True Next Next 'clear all objects Set objFolder=Nothing Set objDir=Nothing Set objFile=Nothing End Sub '========================================================================== ' ' END SUB-ROUTINE DECLERATIONS ' '==========================================================================

Potrebbero piacerti anche