Getting Remote Drive Space on Windows

Posted by Mike on September 9th, 2010 filed in Python, System Administration, Windows

After about a year or so at my current job, as we were still working on upgrading the last few Windows 98 machines to Windows XP, we had a need to check which machines on our network were getting low on disk space. The issue was cropping up because we had Windows XP loaded on several machines that had 10 GB hard drives and a few with 20 GB and one or two with just 4 GB. Anyway, after some digging online, I discovered that the PyWin32 package could accomplish what I needed.

Here is the code that I used:

import win32com.client as com
 
def TotalSize(drive):
    """ Return the TotalSize of a shared drive [GB]"""
    try:
        fso = com.Dispatch("Scripting.FileSystemObject")
        drv = fso.GetDrive(drive)
        return drv.TotalSize/2**30
    except:
        return 0
 
def FreeSpace(drive):
    """ Return the FreeSpace of a shared drive [GB]"""
    try:
        fso = com.Dispatch("Scripting.FileSystemObject")
        drv = fso.GetDrive(drive)
        return drv.FreeSpace/2**30
    except:
        return 0
 
workstations = ['computeNameOne']
print 'Hard drive sizes:'
for compName in workstations:
    drive = '\\\\' + compName + '\\c$'
    print '*************************************************\n'
    print compName
    print 'TotalSize of %s = %f GB' % (drive, TotalSize(drive))
    print 'FreeSpace on %s = %f GB' % (drive, FreeSpace(drive))
    print '*************************************************\n'

Note at the bottom that I used a list. Normally, I would list the computer names of every computer that I wanted to check. Then I would iterate over those names and put together the right path that I needed from a machine with full domain admin rights.

To get this to work, we needed to import win32com.client and call the following: com.Dispatch(“Scripting.FileSystemObject”). This would get us a COM object that we could query to get a disk object. Once we had that, we can ask the disk how much total space it had and how much free space. Looking at this code today, I would combine the two functions into one and return a tuple. As you can see, I do a little bit of math on the result to get it to return the size in gigabytes.

That’s all there is to it. Simple stuff. I suspect that I didn’t write this code completely since the variable names suck. It is probably from an ActiveState recipe or a forum and I forgot to attribute it. If you recognize the code, let me know in the comments!

Print Friendly

  • http://www.engcorp.com Peter Hansen

    My guess is it was from some Microsoft sample or another at one point. Lots of non-Python source with the same naming. See the results at http://www.google.com/codesearch?q=drv+%3D+fso.GetDrive for example.

  • Anonymous

    Possibly, although most of the Microsoft samples I’ve seen on their website are much more verbose.

    – Mike