Hosted PowerShell and LINQ

by Doug Finke on July 21, 2007

in .Net, LINQ, PowerShell

Here are two CSV files (comma separated values). The first file contains the host and port of the machines for different testing configurations.

boxes

The second CSV file contains login information that can be used for each environment from above.

userInfo

I want to join the login information to each environment. There are several ways to do this in PowerShell. One is to construct a single PSObject with a property for each column from both files. Another is to create two PowerShell hash tables.

CreatePipeline and LINQ

After seeing David Aiken’s Hosting PowerShell in a GUI part 1 and part 2 using Visual Studio 2005. I got to thinking, could LINQ simplify working with the PowerShell pipeline.

The answer is yes.

Below, the code creates and opens a PowerShell Runspace and sets up a LINQ query Select Many – Multiple From.

Each from invokes a PowerShell pipeline calling the Import-Csv cmdlet.

The select creates an anonymous type, the element in each column is retrieved and placed in a property. Effectively merging the two CSV files into one “record”.

Wrap the LINQ in parens, call the ToList() method and pass it to the form. The form connects it to the DataSource property on the Data Grid.

program

The Results

form

The equivalent non-LINQ code requires much more plumbing.

  • Creating a class with the variables and properties.
  • A constructor to set the properties.
  • Loop code to traverse the pipeline results and transform them to the object.

Using LINQ over PowerShell pipeline results make it readable and straight forward.

Even though the Import-Csv cmdlet is demonstrated, a PowerShell script works too.

Using LINQ to reduce/simplify code is not unique to PowerShell data.

It’s a great interop story.

{ 1 comment… read it below or add one }

1 Ted G 07.10.09 at 6:24 pm

I wonder what the parameter type in the declaration of frmGrid is.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>