Friday, July 18, 2008

Querying Disk Space on Remote Servers using Batch with WMIC

Time to check the disk free space in GB and percentage on a server volume...

WMIC(Windows Management Instrumentation Command-line) makes another appearance!

Thanks to Tipsmark for this syntax (Response number 17 in this post). I added the /node switch and some error handling / usage to have this batch file work on remote machines.

@ECHO OFF
IF "%~1"=="" goto help
IF "%~2"=="" goto help

@SETLOCAL ENABLEEXTENSIONS
@SETLOCAL ENABLEDELAYEDEXPANSION

@FOR /F "tokens=1-3" %%n IN ('"WMIC /node:"%1" LOGICALDISK GET Name,Size,FreeSpace | find /i "%2""') DO @SET FreeBytes=%%n & @SET TotalBytes=%%p

@SET /A TotalSpace=!TotalBytes:~0,-9!
@SET /A FreeSpace=!FreeBytes:~0,-10!
@SET /A TotalUsed=%TotalSpace% - %FreeSpace%
@SET /A PercentUsed=(!TotalUsed!*100)/!TotalSpace!
@SET /A PercentFree=100-!PercentUsed!

IF %TotalSpace% LSS 0 goto error

@ECHO Total space: %TotalSpace%GB
@ECHO Free space: %FreeSpace%GB
@ECHO Used space: %TotalUsed%GB
@ECHO Percent Used: %PercentUsed%%%
@ECHO Percent Free: %PercentFree%%%

@SET TotalSpace=
@SET FreeSpace=
@SET TotalUsed=
@SET PercentUsed=
@SET PercentFree=
goto end

:error
echo.
echo *** Invalid server or drive specified ***
echo.
goto help

:help
echo.
echo diskfree.cmd
echo.
echo Queries remote server for free disk space.
echo Specify a MACHINENAME and a drive letter to be queried
echo.
echo Example: diskfree.cmd MACHINENAME c:
echo.
goto end


:end


Here's an example of the script being run with a target computer named 'LARS', checking for free space on the [F:] volume:





If parameters are not passed or passed incorrectly(wrong drive letter) the script outputs the following or similar:

2 comments:

kittypee.com said...

Did you overlook SNMP for a reason?
Every Windows server has the ability to run an SNMP server. It can be found the the standard Windows Components, and configured using the the properties of the SNMP Service itself.

The SNMP Service on Windows uses many of the standard SNMP OIDs for Network interfaces, Disks, Memory, etc.

Lars Rasmussen said...

WMI is enabled by default, and SNMP is not. That being said, SNMP is used for monitoring disk space in our shop.

Overlooked? Nope.

I still use SNMP - we poll on an interval with our monitoring system and fire off alerts(emails) to mobile devices. When responding to a disk space alert, this script is used for a quick percentage calculation. I guess I could wait another 5 or 15 minutes for SNMP to poll again, but I'd rather go back to sleep when paged in the middle of the night.