Use Native Methods For Huge Performance Gains

Many PowerShell examples, samples and everything generated by PowerGUI use a common structure to filter out desired objects:

Get-Something | Where-Object { $_.Name –match “pattern” }

This is great for samples and one-off scripts.  It is clear and easy to read.  However, when run in production against large data sources or large numbers of object, this frequently becomes a bottleneck.

This performance hit is especially noticeable when polling remote data sources.  In this example I found in an Operations Manager forum, we query for all objects found in two classes and then filter locally:

Get-MonitoringClass | `
Where-Object {$_.Name –eq “”} | `
Get-MonitoringObject | Where-Object {$_.state –eq “Error”}

In a small demonstration environment of 10-20 servers, this would not be a problem.  However, my environment is a bit larger and this command times out at 1 minute and 45 seconds.

A better way is to use the native methods of the Operations Manager SDK to filter and match those objects required:

Get-MonitoringClass –Name “Microsoft.Windows.Server.2008.Computer” | `
Get-MonitoringObject –Criteria “HealthState = 3”

This ran in about 9 seconds for a huge performance gain.  I would imagine that this saves performance on the server hosting the SDK, my backend database and even the network.

Summary – for production use, take time to make use of native class methods for more efficient code.

This entry was posted in PowerShell and tagged , . 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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s