The other day I posted a VBS function for getting drive utilization. It seems only fair to give PowerShell a chance to play.
The Get-Utilization function also uses WMI via the Get-WMIObject cmdlet. One nice advantage to PowerShell is that I can specify default parameter values. I’ve set the defaults to the %computername% environmental variable and drive C:\. To make the function as seamless as possible, I turn off the error pipeline by setting $ErrorActionPreference to SilentlyContinue. I do the same with the -ErrorAction parameter in line 18. If the Get-WMIObject expression is successful, then $drive.size will have a value and I can carry out my utilization calculations. If it doesn’t exist then there was some problem, perhaps permissions or an invalid drive, in this function I don’t really care. Instead I’ll simply return a value that can’t be mistaken for a drive utilization at line 27.
Assuming a valid drive object was returned I perform a similar calculation as I did in VBScript and write the result to the pipeline. Line 33 shows the function in use. I use an If ElseIf construct to display an appropriate message depending on the value returned by Get-Utilization. Another advantage over VBScript is that I can display the message in a different color depending on the utilization value.
You’re welcome to expand the function. For example, there is no provision for alternate credentials. You could probably add more error handling. I have to leave some fun for you right?
Download the PowerShell file here.