Faster Where-Object In PowerShell

One of the worst features of PowerShell for me is extremely slow performance in loops, especially using items like Where-Object { $_.Name –eq “value” }

For performance critical loops I use inline C#

Here is an example to search data imported from CSV more quickly, to retrieve the relevant line of data:

$Source = @"

using System;
using System.Management.Automation;
namespace FastSearch
    public static class Search
        public static object Find(PSObject[] collection, string column, string data)
            foreach(PSObject item in collection)
                if (item.Properties[column].Value.ToString() == data) { return item; }

            return null;

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp 

$data = Import-Csv "songwriters.csv"

$row = [FastSearch.Search]::Find($data,"Name","Bob Dylan")

In test CSV file to search the CSV data 30k times the C# version took a few minutes, using $data | Where-Object { Name –eq “<name>”} took over 12 hours.

About chentiangemalc

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you're doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.
This entry was posted in Performance, PowerShell. 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