Using WMI with PowerShell

If you aren’t already using WMI to retrieve information from computers in your domain, it’s time to get started. WMI is a goldmine of information and it’s never been easier to access.

I’ll be covering WMI in more detail later as there is so much to go through. For now I’ll demonstrate a short script that can reveal how easy it is to generate useful reports when accessing WMI through PowerShell.

This function will take an array of computer names, attempt to query each of their WMI databases, retrieve the free space available and also calculate the free space percentage. The function accepts pipelining. I have not added any error handling which means if a machine is not configured to let you query its WMI database, you will get a big red error telling you so. Don’t worry though, you can do no damage with the function as it does not set any values. Here is an example of usage and output:

And here is the source

Function Get-FreeSpace {

 Begin {
 $Result = @()


 Process {
 $Drives = Get-WmiObject 'Win32_LogicalDisk' -ComputerName $Computers | where { $_.DriveType -eq 3 }

 $Drives | % {
 $newobj = New-Object System.Object
 $newobj | Add-Member -Name Server -MemberType NoteProperty -Value $_.__Server
 $newobj | Add-Member -Name DriveName -MemberType NoteProperty -Value $_.Name
 $newobj | Add-Member -Name FreeSpace -MemberType NoteProperty -Value ("{0:0.00}GB" -f ($_.FreeSpace / 1GB))
 $newobj | Add-Member -Name Size -MemberType NoteProperty -Value ("{0:0.00}GB" -f ($_.Size / 1GB))
 $newobj | Add-Member -Name PercentFree -MemberType NoteProperty -Value ("{0:0.00}%" -f ($_.FreeSpace * 100 / $_.Size))
 $Result += $newobj

 End {
 return $Result


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s