I hadn’t realized you could use Regular Expressions to manage fixed width text files.

Bill Sempf blogs and talks about the efficient way for Handling fixed width text with Regular Expressions (RegEx) and presents a C# solution.

The PowerShell Solution

The school is 32 characters, the location is 28 characters, and the year is 4 characters.

$records = @"
University of Illinois          Champaign, Illinois         1867
Indiana University              Bloomington, Indiana        1820
University of Iowa              Iowa City, Iowa             1847
University of Michigan          Ann Arbor, Michigan         1817
Michigan State University       East Lansing, Michigan      1855
University of Minnesota         Minneapolis, Minnesota      1851
Northwestern University         Evanston, Illinois          1851
Ohio State University           Columbus, Ohio              1870
Pennsylvania State University   State College, Pennsylvania 1855
Purdue University               West Lafayette, Indiana     1869
University of Wisconsin–Madison Madison, Wisconsin          1848
"@            

$pattern = '^(?<school>.{32})(?<location>.{28})(?<joined>.{4})$'            

ForEach($record in ($records -split "`r`n")) {
    if($record -match $pattern) {
        New-Object PSObject -Property @{
            School   = $matches.school
            Location = $matches.location
            Joined   = $matches.joined
        } | Select School, Location, Joined
    }
}            

# Results
School                           Location                     Joined
------                           --------                     ------
University of Iowa               Iowa City, Iowa              1847
University of Michigan           Ann Arbor, Michigan          1817
Michigan State University        East Lansing, Michigan       1855
University of Minnesota          Minneapolis, Minnesota       1851
Northwestern University          Evanston, Illinois           1851
Ohio State University            Columbus, Ohio               1870
Pennsylvania State University    State College, Pennsylvania  1855
Purdue University                West Lafayette, Indiana      1869
University of Wisconsin–Madison  Madison, Wisconsin           1848 

{ 1 comment }

PowerShell is built on top of .NET. This allows you to tap into the power of the .NET framework as well as any DLLs/Assemblies you build. In version 2 of PowerShell the Add-type cmdlet was added which is the preferred way to load .NET assemblies.

In PowerShell Version 1 that cmdlet is not available so you need to use the one of the Load* static methods found in System.Reflection.Assembly.

[Reflection.Assembly]::Load

Loads an assembly

[Reflection.Assembly]::LoadFile Loads the contents of an assembly file on the specified path
[Reflection.Assembly]::LoadFrom Loads an assembly given its file name or path
[Reflection.Assembly]::LoadWithPartialName Loads an assembly from the application directory or from the global assembly cache using a partial name

Why?

For example, in PowerShell, if you want to encode a Url you can use the UrlEncode method found in the .NET HttpUtility Class.

If you fire up PowerShell and try to call the static method UrlEncode found in System.Web.HttpUtility you’ll get this error.

[System.Web.HttpUtility]::UrlEncode("this is a test")

Unable to find type [System.Web.HttpUtility]: make sure that the assembly containing this type is loaded.

You can solve this by loading the System.Web .NET assembly. This is equivalent to being in the Visual Studio IDE, adding a reference and then adding a using statement.

Using Reflection.Assembly in PowerShell Version 1

[Reflection.Assembly]::LoadFile( `
  'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll')`
  | out-null            

[System.Web.HttpUtility]::UrlEncode("this is a test")

Using Add-Type in PowerShell Version 2

Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::UrlEncode("this is a test")

Additional Reflection.Assembly usage

[void] [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[reflection.assembly]::Load("mscorlib.dll") | Out-Null
[void][system.reflection.assembly]::loadfrom("c:\windows\system32\inetsrv\microsoft.web.administration.dll")

Additional Add-Type usage

Add-Type -AssemblyName "System.Windows.Forms"
Add-Type -AssemblyName "mscorlib.dll"
Add-Type -Path "c:\windows\system32\inetsrv\microsoft.web.administration.dll"

Compiling C# on the fly in Version 2

Add-Type -TypeDefinition @"
public class Test
{
    public static int Add(int n1, int n2)
    {
        return n1 + n2;
    }
}
"@

If you change the signature of the Add method you will get this error:

image

When compiling code on the fly or loading assemblies they cannot be unloaded.

.NET assemblies can’t be unloaded from a session (it’s a .NET thing, not a PowerShell thing) therefore DLLs can’t be unloaded from a session. This means that you can’t update a DLLs once it’s been loaded. We can’t even update the assembly on disk because the file is locked when the assembly is loaded.

- Bruce Payette Windows PowerShell in Action, Second Edition

Another way to use the –Path parameter on Add-Type

You can point to a C# source code file directly.

Add-Type –Path c:\test\Hello.cs

Add-Type is not limited to compiling only C#

You can inline these languages using the –Language parameter CSharp, CSharpVersion3, VisualBasic, JScript.

Notice, F# is not supported. Here is a post How to add an F# type to a PowerShell session that inlines F#.

NOTE: This uses the F# DLLs shipped with .NET 4.0

Add-TypeFSharp -TypeDefinition @"
module MyModule

let Add a b = a + b;;
"@                        

1..10 | % { [MyModule]::Add( $_, $_*2 ) }

Finally

There are additional parameters that the Add-Type cmdlet supports. You can generate a DLL file for the assembly with the specified name in the location, specify compiler parameters, specify assemblies which your code depends on and use wild cards when loading assemblies.

Check out the online help for Add-Type.

{ 6 comments }

PowerShell Hacker #13

by Doug Finke on August 27, 2010

in PowerShell,Raven DB,SQL,Sql Server,WPF

My daughter is set up at the freshman dorms in college. Let’s see what PowerShell goodness is out there.

{ 1 comment }

September 8th, I’ll be on MSDN Webcast: geekSpeak talking about: PowerShell for .NET Developers.

Under the DSI banner, Microsoft has been working for a while on improving the management/automation infrastructure for Windows, with tools like PowerShell (which I like a lot).

  • It was great to watch this PowerShell script unfold from an interaction of 140 character tweets. Jaykul posted it HERE. With it you can do this:

C:\PS> math ‘(42 / 9) * ( cos(.56) ^ 3 ) + Tan 60’

{ 3 comments }

Richard and Greg over on RunAs Radio talked to me about the OData PowerShell Explorer I built and put up on CodePlex.

Check it out. HERE is the podcast.

We talked about:

I want to thank Richard and Greg for having me on, smart guys and smart questions. They got me thinking about next steps for using PowerShell and features to add to the OData PowerShell Explorer.

{ 3 comments }

Rob Conery’s post Redlining C#’s Dynamic Features shows Ruby source and then explores the C# 4.0 dynamic keyword feature to achieve the same results.

So to get my head around the Ruby example, I worked up one way to do it in PowerShell using the New-Module cmdlet, wrapped it in a function and you can see the code below.

Like Ruby, PowerShell lets us assign a string to Address in the first example ($p1) and then in the second example ($p2) to a more complex object without breaking the Person implementation.

Rob Conery’s post goes on to show that C# 4.0 can do the same thing. The dynamic dial is being turned up for this static language.

Rob suggests:

C# is going more and more dynamic – time and feature set have proven that. Maybe it’s time to bend your thinking? Or maybe it’s not…

In either case it is possible to do and should make for interesting discussions.

Function New-Address {
    New-Module -AsCustomObject -Name Address {
        $Number  = $null
        $Street  = $null
        $City    = $null
        $State   = $null
        $Country = $null            

        Export-ModuleMember -Variable *
    }
}            

Function New-Person {
    New-Module -AsCustomObject -Name Person {
        $Name    = $null
        $Address = $null                    

        Export-ModuleMember -Variable *
    }
}            

$p1 = New-Person
$p1.Name = "Mary"
$p1.Address = "Number 17, Cherry Tree Lane"
$p1            

$p2 = New-Person
$p2.Name = "Burt"
$p2.Address = New-Address
$p2.Address.Number = 17
$p2.Address.Street = "Cherry Tree Lane"
$p2.Address.City = "London"
$p2            

# Result
Address                                                              Name
-------                                                              ----
Number 17, Cherry Tree Lane                                          Mary
@{City=London; Country=; Number=17; State=; Street=Cherry Tree Lane} Burt

{ 0 comments }

Alex James, a Program Manager working on the Data Services team at Microsoft, tweeted this:

#OData query to find @jonskeet http://tinyurl.com/jonskeet200000

So, how would you find Jon Skeet using the OData PowerShell Module?

First, download OData PowerShell Explorer.

Then paste this code into the console or run it from ISE (Integrated Scripting Environment).

My OData PowerShell Explorer is extracted in C:\CodePlex\psodata\trunk. Change the directory in the Import-Module to where you extracted the zip.

PowerShell Code

import-module C:\CodePlex\psodata\trunk\modules\OData.psm1
$se = New-ODataService `
  "http://odata.stackexchange.com/stackoverflow/atom"
$se.Users('$filter=Reputation gt 200000')

Results

# Results
AboutMe        : <p>
                 Author of <a href=`http://www.manning.com/affiliate/idevaffiliate.php?id=876_230` rel=`nofollow`>C# in Depth</a>.<br>
                 Currently a software engineer at Google, London.<br>
                 Microsoft MVP (C#, 2003 onwards)
                 </p>

                 <p>Sites:</p>

                 <ul>
                 <li><a href=`http://csharpindepth.com` rel=`nofollow`>C# in Depth</a>
                 <li><a href=`http://msmvps.com/jon.skeet` rel=`nofollow`>Coding blog</a>
                 <li><a href=`http://pobox.com/~skeet/csharp` rel=`nofollow`>C# articles</a>
                 <li><a href=`http://twitter.com/jonskeet` rel=`nofollow`>Twitter updates</a>
                 </ul>

                 <p>Email: skeet@pobox.com</p>

Age            : 34
CreationDate   : 2008-09-26T12:05:05.15
DisplayName    : Jon Skeet
DownVotes      : 295
EmailHash      : 6d8ebb117e8d83d74ea95fbdd0f87e13
Id             : 22656
LastAccessDate : 2010-08-01T21:54:18.477
Location       : Reading, UK
Reputation     : 200869
UpVotes        : 6460
Views          : 138078
WebsiteUrl     : http://csharpindepth.com

{ 0 comments }

Keep the Date September 8

by Doug Finke on August 10, 2010

in MSDN,Microsoft,PowerShell,Webcast,geekSpeak

MSDN Webcast: geekSpeak: PowerShell for .NET Developers with Doug Finke (Level 200)

In this episode of geekSpeak, Microsoft Most Valuable Professional (MVP) Doug Finke takes us on a deep dive into PowerShell from a developer’s point of view. Doug shows techniques for integrating/debugging PowerShell from and to C# code as well as using PowerShell with a Windows Presentation Foundation (WPF) application. He also addresses using reflection at the command line, object pipelining, and PowerShell’s REPL. This geekSpeak is hosted by Glen Gordon andRachel Appel.

The geekSpeak webcast series brings you industry experts in a "talk-radio" format hosted by developer evangelists from Microsoft. These experts share their knowledge and experience about a particular developer technology and are ready to answer your questions in real time during the webcast.

{ 1 comment }

There are at least 6 applications that let you interact with OData. The latest two are for PowerShell and the iPhone:

via OData Primer

{ 0 comments }

PowerShell lets me leverage .Net to do heavy lifting from the command-line

This talk was about the powerful ability to perform advanced tasks through PowerShell and how you can utilize PowerShell on penetration tests.

{ 1 comment }