Welcome to MSDN Blogs Sign in | Join | Help

jaredpar's WebLog

Code, rants and ramblings of a programmer.

Syndication

News

Now Reading

Expert F#

What's a better book to read when learning F#?

Essential WPF

Thus far the best book I've read on WPF. Gets right down to working with WPF and the goals/history.

Purely Functional Data Structures

Reading this book makes me feel like I'm back in college. It will really get your mind going and is best read with a whiteboard handy.

Blog Roll

Eric Lippert
Dustin Campbell
Jon Skeet
Coding Horror
Brian McNamara
Hub FS
Full List

LINQ like functions for PowerShell: Skip-Count

The PowerShell pipeline, is fairly similar to C#/VB’s LINQ.  Both filter a group of elements through a series of transformations which produce a new series of elements.  The devil is in the details of course but I’ll get to that in a future post. 

When using PowerShell I constantly find myself wanting to use various LINQ expressions on a pipeline.  Unfortunately, many LINQ expressions have no built-in equivalent in PowerShell.  Most are fairly straightforward to write but a few are a bit trickier.  In either case, there’s no reason for people needing to figure them out twice.  So I’ll be starting a series on LINQ expressions in PowerShell.

Also, my posts are getting a bit long winded as of late.  This will be a good oppuritunity to get some shorter posts up.

Today's entry is the equivalent of Enumerable.Skip.  The operation takes a count and skips “count” elements in the enumeration.  For PowerShell, it’s the equivalent of skipping “count” elements in the pipeline. 

#============================================================================
# Skip the specified number of items
#============================================================================
function Skip-Count() {
    param ( $count = $(throw "Need a count") )
    begin { 
        $i = 0
    }
    process {
        if ( $i -ge $count ) { 
            $_
        }
        $i += 1
    }
    end {}
}

Example:

PS:) 1..10 | skip-count 5
6
7
8
9
10

Published Tuesday, January 13, 2009 8:00 AM by Jared Parsons

Filed under: ,

Comments

# re: LINQ like functions for PowerShell: Skip-Count @ Friday, January 16, 2009 5:31 PM

Great minds think alike! I actually implemented an assload of these kinds of commands in C# using a Cmdlet. I work with a lot of large sequences and the performance of a compiled C# Cmdlet blows away script-based ones but for my blog I'm gonna convert them to advanced functions.

Here's one that I came up with that you might like:

http://einsteintech.spaces.live.com/blog/cns!89E05724AF67A39E!228.entry

Josh Einstein

# re: LINQ like functions for PowerShell: Skip-Count @ Monday, January 19, 2009 9:25 AM

@Josh,

I love the default "lambda" expression inline in the parameter list.

Jared Parsons

New Comments to this post are disabled
Page view tracker