Friday, February 7, 2014

Remove old IIS files with batch file (running on Task Scheduler)

Script below allows you to remove IIS Logs older than MaxDays days.
You can put it in vbs file and create bat file that will call vbs file:
cscript \.vbs
Then, you can schedule execution of that file using Task Scheduler.
Mostly the script is taken from http://gallery.technet.microsoft.com/scriptcenter/ba67b84a-286e-4256-8a6c-d6579dce2045 (replace interactive pieces of the script with providing the local computer as a target for the script).

MaxDays = 10

Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName

wmiQuery = "Select * from Win32_OperatingSystem" 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set colItems = objWMIService.ExecQuery(wmiQuery) 
    For Each objItem In colItems 
        sWindowsPath = objItem.WindowsDirectory 
    Next 
Set objW3SVC = GetObject( "IIS://" & strComputer & "/W3SVC") 
    For Each objSite In objW3SVC 
        If objSite.Class = "IIsWebServer" Then 
            strLogDir = UCase(objSite.LogFileDirectory) 
                strLogDir = Replace(strLogDir,"%WINDIR%",sWindowsPath,1,1,1) 
                strLogDir = cscript C:\Scripts\VG\deleteoldiisfiles.vbsReplace(strLogDir,"%SYSTEMROOT%",sWindowsPath,1,1,1) 
                strLogDir = Replace(strLogDir,":","$",1,1,1) 
            objLogFolder = "\\" & strComputer & "\" & strLogDir 
            Set oFSO = CreateObject("Scripting.FileSystemObject") 
            Set oFolder = oFSO.GetFolder(objLogFolder) 
            Set colSubFolders = oFolder.Subfolders 
            For Each oSubFolder In colSubFolders 
                If InStr(UCase(oSubFolder),"W3SVC") Then 
                    For Each oFile In oSubFolder.files 
                        If InStr(LCase(oFile.Name),".log") Then 
                             If (Date - oFile.DateCreated > CInt(MaxDays)) Then 
                                oFSO.DeleteFile(oSubFolder & "\" & oFile.Name) 
                            End If 
                        End If 
                    Next 
                End If 
            Next 
        End If 
    Next 

No comments:

Post a Comment