Kaseya Community

Defrag and Chkdsk Script

  • I am very new to Kaseya and honestly a little lost. I know how to use all the basic features but when it comes to the scripting aspect i have no clue.

    I am currently trying to create a script to schedule a disk defrag and chkdsk on the c: drive. Can anyone help me out with this?

     

    Thank you!

  • Hi in-stal

     

    This VBScript will defrag all fixed drives on WindowsXP (Windows7 does its own defrag so no need there). Note that this script writes a file containing the results to :c:\kworking\defrag_logs" (as well as writing to the "Application Log" on the defragged machine. If the folder does not exist it creates it. You may wish to change the location of the results file in the script.

     

    strComputer = "." 

     

    Const DriveTypeFixed = 2

    dim myDate, objShell, FSO, objWMIService, colOperatingSystems, msg, newFolder

    Dim WshShell, RunString, Return

     

    myDate = FormatDateTime(Date, 2)

    myDate = Replace(myDate,"/","-")

    LogFile = "C:\kworking\defrag_logs\defrag_log_" & MyDate & ".log"

     

    set objShell = Wscript.CreateObject("Wscript.Shell") 

    Set FSO = CreateObject("Scripting.FileSystemObject")

    Set Drives = FSO.Drives

     

    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 

    Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")

     

    For Each objOperatingSystem in colOperatingSystems

     

    msg = objOperatingSystem.Caption

     

    If Instr(msg, "Windows XP") > 0 Then

    If  Not FSO.FolderExists("C:\kworking\defrag_logs\") Then

      newFolder = FSO.CreateFolder ("C:\kworking\defrag_logs\") 

    End If

    objShell.logevent 0, "Beginning defrag on WindowsXP "

    For each Drive in Drives

    If Drive.DriveType = 2 then

      RunCmd Drive

    End If

    Next 

      objShell.logevent 0, "Defrag process begun"

    Else

     

    set colVolumes = objWMIService.ExecQuery ("Select * from Win32_Volume where DriveType = 3") ' type 3 is local disk 

    for each objVolume in colVolumes 

        objShell.logevent 0, "Begining defrag analysis routine on drive - " & objVolume.DriveLetter 

    errResult = objVolume.DefragAnalysis(blnRecommended, objReport) 

        If errResult = 0 then 

    objShell.logevent 0, "Average file size: " & objReport.AverageFileSize & vbCrLf & _

    "Average fragments per file: " & objReport.AverageFragmentsPerFile  & vbCrLf & _

    "Cluster size: " & objReport.ClusterSize & vbCrLf & _

    "Excess folder fragments: " & objReport.ExcessFolderFragments & vbCrLf & _

    "File percent fragmentation: " & objReport.FilePercentFragmentation & vbCrLf & _

    "Fragmented folders: " & objReport.FragmentedFolders & vbCrLf & _

    "Free space: " & objReport.FreeSpace & vbCrLf & _

    "Free space percent: " & objReport.FreeSpacePercent & vbCrLf & _ 

    "Free space percent fragmentation: " & objReport.FreeSpacePercentFragmentation & vbCrLf & _ 

    "MFT percent in use: " & objReport.MFTPercentInUse & vbCrLf & _ 

    "MFT record count: " & objReport.MFTRecordCount & vbCrLf & _ 

    "Page file size: " & objReport.PageFileSize & vbCrLf & _ 

    "Total excess fragments: " & objReport.TotalExcessFragments & vbCrLf & _ 

    "Total files: " & objReport.TotalFiles & vbCrLf & _ 

            "Total folders: " & objReport.TotalFolders & vbCrLf & _ 

            "Total fragmented files: " & objReport.TotalFragmentedFiles & vbCrLf & _ 

    "Total MFT fragments: " & objReport.TotalMFTFragments & vbCrLf & _ 

    "Total MFT size: " & objReport.TotalMFTSize & vbCrLf & _ 

    "Total page file fragments: " & objReport.TotalPageFileFragments & vbCrLf & _ 

    "Total percent fragmentation: " & objReport.TotalPercentFragmentation & vbCrLf & _ 

    "Used space: " & objReport.UsedSpace & vbCrLf & _ 

    "Volume name: " & objReport.VolumeName & vbCrLf & _ 

    "Volume size: " & objReport.VolumeSize

     

            If blnRecommended = True Then 

                objShell.logevent 0, "The " & objVolume.DriveLetter & " drive should be defragged. Beginning defrag now..." 

    strerrResult = objVolume.Defrag()

        if strerrResult <> 0 then  

            strEVENT = 1       

        else 

            strEvENT = 0 

        end if  

        Select Case strerrResult 

            case  0 msg = "The defrag completed without error" 

            case  8 msg = "Another defrag session is open" 

            case 10 msg = "Not enough free space to run defrag, we need 15%" 

            case else msg = "Unknown error" 

        end select 

        objShell.LogEvent strEVENT, "The Defrag_All_Fixed_Drives.vbs script exited with an error code of " _ 

            & strerrResult & " for volume " & objVolume.DriveLetter & vbCRLF & vbCRLF & msg 

            Else 

                objShell.logevent 0, "This volume does not need to be defragged." 

            End If 

     

    Else

    objShell.logevent 0, "Defrag threw the following error - " & errResult

    End if

    Next 

    End If

    next

     

    Sub RunCmd(DriveString)

    Set WshShell = WScript.CreateObject("WScript.Shell")

    RunString = "%comspec% /c echo " & WeekDayName(WeekDay(Now), True) & " " & Now & " " & DriveString

    Return = WshShell.Run(RunString & " >> " & LogFile & " 2>&1", 0, TRUE)

    RunString = "%comspec% /c %WINDIR%\System32\Defrag.exe " & DriveString & " -f"

    Return = WshShell.Run(RunString & " >> " & LogFile & " 2>&1", 0, TRUE)

    Set WshShell = Nothing

    End Sub

  • For chkdsk, make a Kaseya Procedure that executes this Shell Command as the System Account:

    echo Y|chkdsk.exe C: /f /r

    This will cause the system to run a chkdsk on the next reboot (but will not reboot the computer). Then set up Application Log Monitoring on your systems and use "Event Log Alerts" to look for "WinLogon 1001" Information event and have it send you an email when it finds one. The email will look something like this:

    Log: Application

    Type: Informational

    Event: 1001

    Agent Time: 2012-05-01 08:14:33Z

    Event Time: 03:08:04 PM 1-May-2012 UTC

    Source: Winlogon

    Category: None

    Username: N/A

    Computer: ComputerNameHere

    Description: Checking file system on C:

    The type of the file system is NTFS.

    Cleaning up minor inconsistencies on the drive.

    Cleaning up 1233 unused index entries from index $SII of file 0x9.

    Cleaning up 1233 unused index entries from index $SDH of file 0x9.

    Cleaning up 1233 unused security descriptors.

    CHKDSK is verifying Usn Journal...

    Usn Journal verification completed.

    CHKDSK is verifying file data (stage 4 of 5)...

    File data verification completed.

    CHKDSK is verifying free space (stage 5 of 5)...

    Free space verification is complete.

    CHKDSK discovered free space marked as allocated in the volume bitmap.

    Windows has made corrections to the file system.

     39021884 KB total disk space.

     28936240 KB in 63741 files.

        21036 KB in 6369 indexes.

            0 KB in bad sectors.

       178908 KB in use by the system.

        65536 KB occupied by the log file.

      9885700 KB available on disk.

         4096 bytes in each allocation unit.

      9755471 total allocation units on disk.

      2471425 allocation units available on disk.

    Internal Info:

    10 23 01 00 ea 11 01 00 38 4e 01 00 00 00 00 00  .#......8N......

    c1 0a 00 00 04 00 00 00 f1 0f 00 00 00 00 00 00  ................

    de ed de 04 00 00 00 00 92 5d 74 46 00 00 00 00  .........]tF....

    ec 46 0a 4a 00 00 00 00 92 15 01 5e 03 00 00 00  .F.J.......^....

    b0 51 8e ec 00 00 00 00 9c 49 28 e3 04 00 00 00  .Q.......I(.....

    99 9e 36 00 00 00 00 00 b0 39 08 00 fd f8 00 00  ..6......9......

    00 00 00 00 00 c0 20 e6 06 00 00 00 e1 18 00 00  ...... .........

    Windows has finished checking your disk.

    Please wait while your computer restarts.