Sunday, July 6, 2008

Using .NET

I just want to give you guys a quick example of how easy it is to use .NET in your PowerShell scripts. Let's say Alfred E. Neuman has quit The Company, and I want to take all of his oncall shifts. In this scenario I have a text file called oncall.txt:

PS C:\Users\timjohnson\Documents> cat oncall.txt
20080613 timjohnson
20080614 bfong
20080615 mherzog
20080616 aneuman
20080617 timjohnson
20080618 bfong
20080619 mherzog
20080620 aneuman
20080621 timjohnson
20080622 bfong

I can create a regular expression object that will do the dirty work of replacing his name with mine like this:

PS C:\Users\timjohnson\Documents> $regex = new-object System.Text.RegularExpressions.Regex "\baneuman\b"
PS C:\Users\timjohnson\Documents> cat oncall.txt | foreach {$regex.Replace($_, "timjohnson")}
20080613 timjohnson
20080614 bfong
20080615 mherzog
20080616 timjohnson
20080617 timjohnson
20080618 bfong
20080619 mherzog
20080620 timjohnson
20080621 timjohnson
20080622 bfong

Powershell not only let me use $regex as a System.Text.RegularExpressions.Regex object, but it even lets me do tab completion for method names. Sweet.

No comments: