pythonpowershellcmdhard-drive

Get the serial number of the hard disk who host windows os


I'm trying to get the serial number of the hard disk who host windows os in a consistant way through python calling windows cmd from subprocess

So far using :

wmic diskdrive get serialnumber,index

Which give me back something like :

Index  SerialNumber
1      000000001536
0      0025_XXXX_2142_XXXX.
2      000000001536

However the first, nor the index 0 is not always the hardrive with the OS... (as mentionned in the answer in Get hard disk serial number from local disk in batch)

Is there a command to get the hard drive serial number of where is installer the Windows OS ?

Thanks,


Solution

  • Thanks to your suggestions :

    For windows > 7, In a powershell with the SystemDrive environnement variable, the serial number of the current used os can be found with :

    get-partition -DriveLetter ($Env:SystemDrive).Replace(':','') | get-disk | % {$_.SerialNumber}
    

    For older versions of windows,in cmd.exe, wmic can be used with :

    wmic /namespace:\\root\microsoft\windows\storage path msft_disk WHERE "IsSystem='TRUE'" get serialnumber
    

    In python :

    import subprocess
    
    def get_serial():
        try:
            cmd = r'wmic /namespace:\\root\microsoft\windows\storage path msft_disk WHERE "IsSystem=\'TRUE\'" get serialnumber'.replace(
                "\\'", "'")
            serial = subprocess.check_output(cmd)
    
    
        except:
            cmd = "get-partition -DriveLetter ($Env:SystemDrive).Replace(':','') | get-disk | % {$_.SerialNumber}"
            ouput = subprocess.run(["powershell", "-Command", cmd], capture_output=True)
            serial = ouput.stdout
    
        return serial
    

    Note that calling a powershell and get-partition is fairly slow...