VBScript: Check for Low Disk Space and Report to Event Viewer

This code is part of a bigger project I’m working on. It checks the disk space for each logical drive and, if the space is below one gigabyte, reports it to Event Viewer at a max of once per day.

'****************************************************************************
' This script created by Chrissy LeMaire ([email protected])
' Website: http://netnerds.net/
'
' NO WARRANTIES, etc.
'
' This script checks hard drives for less than 1GB of space.
'
' Requirements -- ability to read WinNT://, create events and read WMI
'
' This script has only been tested on Windows Server 2003.
'
' "What it does"
' 1. Gets a list of computers on a domain
' 2. Checks for disk space
' 3. If disk space < 1 GB, add to Event Viewer but not more than once a day.
'*****************************************************************************

On Error Resume Next 'Ignore errors

Set objAdRootDSE = GetObject("LDAP://RootDSE")
Set objRS = CreateObject("adodb.recordset")

  varConfigNC = objAdRootDSE.Get("defaultNamingContext")
  strConnstring = "Provider=ADsDSOObject"
  strWQL = "SELECT * FROM 'LDAP://" & varConfigNC & "' WHERE objectCategory= 'Computer' and OperatingSystem = 'Windows*Server*'"
  objRS.Open strWQL, strConnstring
    Do until objRS.eof
       Set objServer = GetObject(objRS.Fields.Item(0))
       strServerName = objServer.CN
       Call GetDiskSpaceAddEvent(strServerName)
       objRS.movenext
       Set objServer = Nothing
    Loop
  objRS.close

Set objRS = Nothing
Set objAdRootDSE = Nothing

'-----------------------------------------------------------------------
'
'    Do the Dirty Work
'
'-----------------------------------------------------------------------

Sub GetDiskSpaceAddEvent(strComputer)
myDate = date2String(strComputer,"-24")

Set objWMIService = GetObject("winmgmts:"  & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery  ("Select DeviceID, FreeSpace from Win32_LogicalDisk where DriveType = 3") 'Grab the name and the free space for fixed drives

    For Each objItem in colItems
    MBFree = formatnumber((objItem.FreeSpace/1048576),2)
        If MBFree > 1000 Then 'Convert to MB then check for < 1GB
            theQuery = "SELECT * FROM Win32_NTLogEvent WHERE Eventcode = '1000' and Type = 'Error' and LogFile='System' and SourceName = 'Low Disk Space' and TimeWritten  >= '" & myDate & "' and Message like '%" & objItem.DeviceID & "%" & strComputer & "%'"

            Set colLoggedEvents = objWMIService.ExecQuery (theQuery)
                If colLoggedEvents.Count = 0 Then
                    runThis =  "%COMSPEC% /c eventcreate /s " & strComputer & " /so ""Low Disk Space"" /T Error /ID 1000 /L System /D ""The size of disk " & objItem.DeviceID & " on " & StrComputer & " has dropped below 1 Gigabyte (" & MBFree & " MB free)."""
                    WindowStyle = 0 'Do not pop up a dos box
                    Set WshShell = WScript.CreateObject("WScript.Shell") 'generate the object
                    Call WshShell.Run (runThis, WindowStyle, false) 'execute the dos command listed above (COMSPEC = cmd.exe)
                    Set WshShell = Nothing
                End If
            Set colLoggedEvents = Nothing
        End If
    Next

End Sub

'-----------------------------------------------------------------------
'
'    Supporting Date Functions to convert WMI date to human readable dates
'
'-----------------------------------------------------------------------

'The function listed below only works in 2k3 and XP. So we use the manual ones below.
'Function date2WMI(theHourDiff)
'Set WMIDate = CreateObject("WbemScripting.SWbemDateTime")
'WMIDate.SetVarDate DateAdd("hh", theHourDiff, Now())
'Date2WMI = WMIDate.Value
'End Function

    Function string2Date(dtmInstallDate)
        WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
             Mid(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
                 & " " & Mid (dtmInstallDate, 9, 2) & ":" & _
                     Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
                         13, 2))
          string2Date   = WMIDateStringToDate
    End Function

        Function date2String(strComputer,theOffset)
            Set objSWbemServices = GetObject("winmgmts:\.\root\cimv2")
            Set colTimeZone = objSWbemServices.ExecQuery ("SELECT * FROM Win32_TimeZone")
            For Each objTimeZone in colTimeZone
                strBias = objTimeZone.Bias
            Next

            dtmCurrentDate = date + theOffset
            'response.write dtmCurrentDate
            dtmTargetDate = Year(dtmCurrentDate)

            dtmMonth = Month(dtmCurrentDate)
            If Len(dtmMonth) = 1 Then
                dtmMonth = "0" & dtmMonth
            End If

            dtmTargetDate = dtmTargetDate & dtmMonth

            dtmDay = Day(dtmCurrentDate)
            If Len(dtmDay) = 1 Then
                dtmDay = "0" & dtmDay
            End If

            dtmTargetDate = dtmTargetDate & dtmDay & "000000.000000"
            dtmTargetDate = dtmTargetDate & Cstr(strBias)

            date2String = dtmTargetDate
        End Function

WScript.Quit

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in VBScript
8 comments on “VBScript: Check for Low Disk Space and Report to Event Viewer
  1. Lam Doan says:

    Hi Chrissy,
    Could you tell me the requirement to run the your VB scripts that check for low disk space and to change the script to increase the threshold from 1GB to 15GB.
    I appreciate your reply..

  2. Chrissy says:

    Hey Lam,
    I hear that the script must be run as a domain administrator though I haven’t tested it (I’ll do that tomorrow). While I think that’s a bit extreme, others say “Well that’s privileged information. You don’t just want anyone on the domain knowing about your logical disk configuration.” We’ll see!

    As for changing it to 15 gigs, try changing 1048576 to 15728640 (That’s 1048576 X 15) Let me know how that works :)

    Chrissy

  3. hi chrissy,

    i’m looking for a script that will send “low disk space” reports, from my servers, via email. do you have anything that will do this?

    regards
    roly

    p.s. i have absolutely no scripting experience at all, so i do find this task very difficult. my apologies

  4. Fikret says:

    I need too, via e-mail. I heard 1 program that is serversalive but ididnot test it.

  5. Hieu Truong says:

    I’m also looking for script with email feature

    Cheers!!
    Hieu

  6. Hieu Truong says:

    I’ve found one that does emailing at this link http://www.lynchconsulting.com.au/blog/index.cfm/2007/2/11/Disk-space-monitoring-script-for-windows

    NB! I hope I didn’t offence you Chrissy

    Cheers!
    Hieu Truong

  7. Andrew says:

    Chrissy,

    this script is exactly what i was looking for. except i am querying machines that are in a dmz without a domain. anyway to pass a text file with the server list than querying a domain. and/or run the script locally and write the event.

    thank you very much for any help you can provide.

  8. MattB says:

    Great script, I got it to run and I can see it logging into the servers, however no events are produced in the log.

    As the script is a bit old, I was wondering if its still ok to work or am I doing something wrong.

    Thanks (Great site btw)

    PS I change the disk size threshold so it should have alerted me

1 Pings/Trackbacks for "VBScript: Check for Low Disk Space and Report to Event Viewer"
  1. Troubleshooting Windows Server Disk Space Issue

    One of my baby (Windows 2003 small business server) was having low disk space error yesterday. Its not the first time this Windows Server low disk space on its C: drive (system drive). I have do necessary housekeeping, cleanup temporary files.
    After …

Leave a Reply

Your email address will not be published. Required fields are marked *

*