Get Percent Free Space

I’ve put together a function that will return the percentage free space on a given logical drive for a specified server. The function in the following script is really doing all the hard work. The rest of the script is simply a demonstration on how to call the function. The script uses WMI and queries the Win32_LogicalDisk for the size and freespace properties. With these values it’s pretty simple to calculate a percentage.

‘GetPercentFreeDrive.vbs

specify alternate credentials for remote systems
strUsername=”"
strPassword=”"

strSrv=InputBox(“What computer do you want to query”,”Get Percent Free”,”localhost”)

strDeviceID=InputBox(“What drive do you want to query?”,”Get Percent Free”,”c:”)

WScript.Echo UCase(strDeviceID) & ” on ” & UCase(strSrv) & ” has ” & GetPercent(strSrv,strDeviceID,strUsername,strPassword) & ” free space.”

Function GetPercent(strSrv,strDeviceID,strUsername,strPassword)
‘deviceID is the drive letter and colon, eg E: with no trailing \

On Error Resume Next
Dim SWBemlocator,objWMI,objRef
Const wbemFlagReturnImmediately=&h10
Const wbemFlagForwardOnly=&h20

strQuery=”Select DeviceID,Size,FreeSpace from Win32_LogicalDisk WHERE DeviceID=’” & strDeviceID & “‘”

‘strip out any trailing \ if found
If Right(strDeviceID,1)=”\” Then strDeviceID=Replace(strDeviceID,”\”,”")

‘validate strDeviceID
If Len(strDeviceID)=2 And Right(strDeviceID,1)=”:” Then

Set SWBemlocator = CreateObject(“WbemScripting.SWbemLocator”)
SWBemlocator.Security_.ImpersonationLevel=3
SWBemlocator.Security_.AuthenticationLevel=WbemAuthenticationLevelPktPrivacy
Set objWMI=SWBemlocator.ConnectServer(strSrv,”\root\CIMV2″,strUsername,strPassword)

Set objRef=objWMI.ExecQuery(strQuery,”WQL”,wbemForwardOnly+wbemFlagReturnImmediately)

For Each dev In objRef
iFreeSpace=dev.FreeSpace
iSize=dev.Size
Next

If iSize=”" Then

GetPercent=”Drive Not Found”
Else
GetPercent=FormatPercent(iFreeSpace/iSize,2)
End If

Else
GetPercent=”ERROR”

End If

End Function

Technorati Tags:



Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to FriendFeed Post to Google Buzz Post to Ping.fm Post to Reddit Post to Slashdot Post to StumbleUpon Post to Technorati

This entry was posted in Scripting and tagged , . Bookmark the permalink.

Comments are closed.