Announcement

Collapse
No announcement yet.

Disk Defragmentation support both 32 and 64 bit

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Disk Defragmentation support both 32 and 64 bit

    You can defragment endpoint disks using below script,



    import os;
    defragmentation=os.popen('defrag.exe /C').read()
    print(defragmentation);



    Note: NO STDOUT text. Check success or failure state of script.




  • #2
    Hi all,

    Please refer updated procedure for disk defragmentation,

    Code:
    import os; 
    import ctypes
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)
    
    with disable_file_system_redirection():
        out=os.popen('defrag.exe /C').read()
        print(out);

    Attached Files

    Comment


    • #3
      Hi mkannan,

      Does this script work as well in SSD?

      Thank you,
      Alfie

      Comment


      • #4
        Hi alfie013

        Yes, it will support SSD hard disk if windows 'defrag.exe' tool works with SSD.

        Thanks
        Kannan

        Comment


        • #5
          Hi mkannan,

          Can you please add on the script to check first the HDD/ssd before defragging it. For example, I run the Analyze and if the result is 0 meaning no need to defrag else if 1 or above it will defrag the HDD/SSD.

          Thank you,
          Alfie

          Comment


          • #6
            Hi alfie013

            We will analyze and let you know the update soon.


            Thank you.

            Comment


            • #7
              Hi,

              Please use the script to perform defragmentation after analysis of fragments.

              Note:
              The script analyzes all the Drives for fragments. Checks whether the fragmented rate is 0% then the script prints only analyzed report otherwise, the script performs complete defragmentation operation and prints the report

              Code:
              def ExecuteCMD(CMD, OUT = False):
                  import ctypes
                  class disable_file_system_redirection:
                      _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
                      _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
                      def __enter__(self):
                          self.old_value = ctypes.c_long()
                          self.success = self._disable(ctypes.byref(self.old_value))
                      def __exit__(self, type, value, traceback):
                          if self.success:
                              self._revert(self.old_value)
                  from subprocess import PIPE, Popen
                  with disable_file_system_redirection():
                      OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
                  out, err = OBJ.communicate()
                  RET = OBJ.returncode
                  if RET == 0:
                      if OUT == True:
                          if out != '':
                              return out.strip()
                          else:
                              return True
                      else:
                          return True
                  else:
                      return False
              
              def writeFile(con, ext):
                  import os
                  import random
                  FILEPATH = os.path.join(os.environ['TEMP'], str(random.randint(1, 10000))+ext)
                  with open(FILEPATH, 'w') as f:
                      f.write(con)
                  return FILEPATH
              
              ## batch script to find all drives
              bat=r'''@echo off
              for /f "tokens=2 delims==" %%d in ('wmic logicaldisk where "drivetype=3" get name /format:value') do echo %%d'''
              
              import os
              import re
              file=writeFile(bat, '.bat')
              if os.path.isfile(file):
                  LD=ExecuteCMD(file, True).split()
                  i=0
                  AR=''
                  while i<len(LD):
                      AR+=ExecuteCMD('defrag '+LD[i].strip()+' /A', True)
                      i+=1
                  CO=re.findall(r'Total\sfragmented\sspace\s+\=\s[0-9]+\%', AR)
                  CP=0
                  NCE=len(CO)
                  for i in CO:
                      obj=re.search('[0-9]+', i)
                      CP+=int(obj.group())
                  if CP/NCE!=0:
                      print ExecuteCMD('defrag /C', True)
                  else:
                      print AR
              
              ## cleans the batch script file
              os.remove(file)
              Sample Output:
              Click image for larger version

Name:	Check and Perform Disk Fragmentation.png
Views:	1
Size:	47.8 KB
ID:	8695

              Script File:
              [ATTACH]n8696[/ATTACH]

              Please let us know your feedback.
              Thank you.

              Comment

              Working...
              X