HDD surface scan to remap all volumes

Please use the script for check and fix your disk error on entire HDD

## HDD surface scan to remap all volumes
import os
import re
from subprocess import PIPE, Popen
def excmd(cmd):
    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)
    
    try:
        with disable_file_system_redirection():
            p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
        ot, er = p.communicate()
        return ot
    except:
        return ''

def fapat(pat, ot):
    try:
        fa = re.findall(pat, ot)
        return fa
    except:
        return []

def sepat(pat, ot):
    try:
        m = re.search(pat, ot)
        if m:
            f = m.group()
            return f
        else:
            return ''
    except:
        return ''

def wrfile(fname, scont, mode):
    with open(fname, 'w') as f:
        f.write(scont)
    return os.path.abspath(fname)

## assigns available letter to system reserved partition
DrLets = ['A:', 'B:', 'C:', 'D:', 'E:', 'F:', 'G:', 'H:', 'I:', 'J:', 'K:', 'L:', 'M:', 'N:', 'O:', 'P:', 'Q:', 'R:', 'S:', 'T:', 'U:', 'V:', 'W:', 'X:', 'Y:', 'Z:']
ADrLets = []
sRDrs = []
rcls = []
fnls = []
osDr = os.environ['SYSTEMDRIVE']
nD = fapat(r'Disk\s[0-9]+', excmd('echo list disk | diskpart'))
for i in nD:
    fname = '{}{}{}.txt'.format(os.environ['SYSTEMDRIVE'], os.sep, i)
    scont = 'select {}
list volume'.format(i)
    nV = excmd('diskpart /s "{}"'.format(wrfile(fname, scont, 'w')))
    sRAsAl = sepat(r'Volume\s[0-9]+\s+System\sRese', nV)
    fnls.append(fname)
    if sRAsAl != '':    
        sRV = sepat(r'Volume\s[0-9]+', sepat(r'Volume\s[0-9]+\s+System\sRese', nV))
        scont += '
select {}
'.format(sRV)
        ADrLets.extend(list(set(DrLets) - set(fapat(r'[A-Z]:', excmd('wmic logicaldisk get name')))))
        scont += 'assign letter={}'.format(ADrLets[0].replace(':', ''))
        rscont = scont.replace('assign', 'remove')
        rcls.append(rscont)
        excmd('diskpart /s "{}"'.format(wrfile(fname, scont, 'w')))
        scont = 'select {}
list volume'.format(i)
        excmd('diskpart /s "{}"'.format(wrfile(fname, scont, 'w')))
    else:
        pass

## execute commands
ls = fapat(r'[A-Z]:', excmd('wmic logicaldisk where drivetype=3 get name'))
ls.remove(osDr)
try:
    cls = ' '.join(ls)
    l1 = '{}{}{}'.format('='*4, 'scan and fix on all (including system drive) otherthan os drive', '='*4)
    if len(cls) > 2:
        c1 = excmd('for %i in ({}) do @echo y | chkdsk %i /f'.format(cls))
    else:
        c1 = excmd('echo y | chkdsk {} /f'.format(cls))
except:
    l1 = None
    c1 = None

l2 = '{}{}{}'.format('='*4, 'only scans os drive', '='*4)
c2 = excmd('chkdsk')
l3 = '{}{}{}'.format('='*4, 'schedule scaning and fixing of os drive', '='*4)
c3 = excmd('echo y | chkdsk /f')
l0 = '{}{}{}'.format('='*4, 'smart checking of harddisk', '='*4)
c0 = excmd('wmic diskdrive get status')

## cleans up caches of the program
if len(rcls) == 0:
    os.remove(fnls[0])
elif len(rcls) == 1:
    excmd('diskpart /s "{}"'.format(wrfile(fnls[0], rcls[0], 'w')))
    os.remove(fnls[0])
else:
    for c, fn in zip(rcls, fnls):
        excmd('diskpart /s "{}"'.format(wrfile(fn, c, 'w')))
        os.remove(fn)

with open(''.join([os.environ['SYSTEMDRIVE'], os.sep, 'output.txt']), 'w') as f:
    f.write(l0+'
'+c0+'
'+l1+'
'+c1+'
'+l2+'
'+c2+'
'+l3+'
'+c3)
with open(''.join([os.environ['SYSTEMDRIVE'], os.sep, 'output.txt']), 'r') as f:
    print f.read()

sample output:

script to export:

20161205-HDD-surface-scan-to-remap-all-volumes.json (5.43 KB)

Run status: Failed.

Traceback (most recent call last): File “<string>”, line 98, in <module> IndexError: list index out of range

Hi @Sergey

we will check the procedure and update you soon.

Hi @Sergey

As we have checked the outcome of the script, the script needs disk part utility for fixing errors for System Reserved Space - your Outcome seems that your machine has no disk part utility. Hence we recommend this script https://forum.mspconsortium.com/forum/script-library/6352-fix-disk-errors-for-all-partitions-at-once to perform fixing disk errors except System Reserved Space.

Note: you have an issue with the outcome of the new script but soon we will solve it as per the comment https://forum.mspconsortium.com/forum/script-library/6352-fix-disk-errors-for-all-partitions-at-once