Search This Blog

Saturday, December 27, 2014

Studying for PowerShell and Regex

At work, PowerShell with Regex is used for log search and hence, I am putting hours to learn these two together. I look at this as a good opportunity to learn these two as this is something that requires time to practice and having opportunities to use these two are great ways to learn them.

I tried to learn PowerShell a few times but never really reached a level where I felt comfortable but at this time, I am reading through Windows PowerShell Cookbook and finding that PowerShell has gone through many changes and many new commands.
For instance, I just ran into Invoke-WebRequest whose aliases are 'iwr', 'curl', or 'wget' I remember that we had to create new object using System.Net.WebRequest but with this new command, I don't see the needs. Good addition! In fact, there are many new commands and their alias makes it easy to transition to PowerShell world and as for me this script from the book really helped me to learn alias as I learn PowerShell.
But the most surprising addition to the latest PowerShell is readline library. With readline library, you can turn cmd window into something completely different. One of PowerShell author at Microsoft has implemented really nice module based on this PsReadline library and you should get it from here if you have done so. This will make PowerShell learning quite pleasant.

For regular expression we all know that it is more powerful and yet complicated than wildcard matching. I've looked through a book and some MSDN site but I have found Mastering Regular Expression much more complete than any other sources. So I picked up this book and practice it via PowerShell interface. In PowerShell we can run Regex using "-match" operator in PowerShell. Here is an example.

 PS C:\Temp> "12" -match "\b([1-9]|1[012])\b"  
 True  
 PS C:\Temp> "15" -match "\b([1-9]|1[012])\b"  
 False  

At first, I did not use "\b" which is word boundary. Without this it was producing incorrect result. I won't explain all the details of Regex here as I don't know enough but again point you to the Mastering Regular Expression. ;-)

If anyone is interested in learning these two, try these two books. ;-)

No comments:

Post a Comment