Working with multiple CIM objects

Many of the CIM objects we work with in our computers come in multiple instances – disks and network cards are a couple of examples. Many times when you see examples you’ll see something like this:

$disks = Get-WmiObject -Class Win32_LogicalDisk

foreach ($disk in $disks){
  if ($disk.Size -gt 0) {
    $disk | select DeviceId,
    @{N=’Free’; E={[math]::Round($disk.FreeSpace/1GB, 2)}},
    @{N=’Size’; E={[math]::Round($disk.Size/1GB, 2)}},
    @{N=’PercUsed’; E={[math]::Round((($disk.Size – $disk.FreeSpace) / $disk.Size) * 100, 2)}}

Get a collection of objects. Iterate through them with foreach and do something.

You can, and should, do this as a pipeline operation. The code above is really a hangover from VBScript coding.

Converting the above to a pipeline gives

Get-WmiObject -Class Win32_LogicalDisk |
where Size -gt 0 |
foreach {
    $_ | select DeviceId,
    @{N=’Free’; E={[math]::Round($_.FreeSpace/1GB, 2)}},
    @{N=’Size’; E={[math]::Round($_.Size/1GB, 2)}},
    @{N=’PercUsed’; E={[math]::Round((($_.Size – $_.FreeSpace) / $_.Size) * 100, 2)}}

NOTE – before anyone starts complaining yes I know you can use a  filter on Get-WmiObject I’m explaining the principle! Also, I know that you could go straight into the select on the pipeline but if you want to add extra processing e.g. send an email if the disk is more than 80% used you need the foreach

You can do similar things with NICs for example

Get-WmiObject -ClassName Win32_PerfFormattedData_Tcpip_NetworkInterface |
where CurrentBandwidth -gt 0 |
foreach {
   $props = [ordered]@{
     Name = $psitem.Name
     Computer = $psitem.PSComputerName
     PercUtilisation = (($psitem.BytesTotalPersec * 8) / $psitem.CurrentBandWidth) * 100
   New-Object -TypeName PSObject -Property $props

} |
where PercUtilisation -gt 0.5 |
foreach {
   $text =  @”
   $($_.Name) on $($_.Computer)
   Bandwidth utilized:  $($_.PercUtilisation) %

Rather than displaying $text send an email if the utilisation is too big. 

where PercUtilisation -gt 0.5

is used so I actually get to see results. You probably want 60% or more on your production machines

This entry was posted in PowerShell and CIM, PowerShell and WMI. Bookmark the permalink.

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