Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Learn More about PowerShell and Regular Expressions

Posted on February 5, 2020February 5, 2020

For many Windows-oriented IT Pros, and I used to be one of them, regular expressions was an arcane topic that was too hard to learn. And we never really had a compelling need to learn because we were busy clicky-clicking everything. Then came PowerShell and we discovered, or maybe rediscovered, a whole new way to work. Managing from a command prompt is actually quite liberating.  Today I'd say that if you don't have at least some regular expression skill, you are missing out. Even though PowerShell is all about objects in the pipeline, there are plenty of opportunities where being able to parse a string of text is invaluable.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

As an example, here is a function that is part of a larger project which is why it has a non-standard name. The function isn't supposed to be exposed to the user.

Function GitStat {
    param()
    if (Test-Path .git) {
        $s = (git status --porcelain).trim()
        $untracked = ($s). Where({$_ -match "^\?\?"})
        $add = ($s).where({$_ -match "^A"})
        $del = ($s).where({$_ -match "^D"})
        $mod = ($s).where({$_ -match "^M"})
        [regex]$rx = "\*.\S+"
        #get the matching git branch which has the * and split the string to get only the branch name
        $branch = $rx.match((git branch)).value.split()[-1]
        Write-Host "[" -NoNewline -ForegroundColor Cyan
        Write-Host "$branch : " -NoNewline -ForegroundColor Yellow
        Write-Host "+$($add.count)" -NoNewline -ForegroundColor Green
        Write-Host " ~$($mod.count)" -NoNewline -ForegroundColor Cyan
        Write-Host " -$($del.count)" -NoNewline -ForegroundColor Red
        Write-Host " ?$($untracked.count)" -NoNewline -ForegroundColor Magenta
        Write-Host "] " -NoNewline -ForegroundColor Gray
    }
}

The function parses the output of a git command and writes a colorized summary to the host.

Git status with PowerShell

Without getting too much into the code, I am using regular expressions to build a string that shows the current branch, and the number of added, modified, deleted, and untracked files. Here's another use case for regular expressions.

In my modules, I've started adding online help links to help documentation. The Select-String cmdlet, which can use a regular expression pattern, makes it easy to discover which files need to be updated.

Finding data with Select-String

In this case, the pattern is a simple string. And the list of files is short enough that it isn't difficult to know what files I need to edit. But I could also use a pattern to find files that are missing the link.

Finding missing data with Select-String

Even better, because Select-String writes an object to the pipeline, I can open the files directly in VS Code. Either of these examples will get the job done.

dir docs\*.md | select-string -Pattern "online version:\s+(?!\w+)" | foreach-object { code $_.path }
#or
code (dir docs\*.md | select-string -Pattern "online version:\s+(?!\w+)").path

If by this point you are feeling you need to learn more, I have you covered. I recently finished a new Pluralsight course on PowerShell and Regular Expressions. In it, I teach regular expression fundamentals and basic techniques. Click here to see a short video overview. You'll probably use them 90% of the time in PowerShell. But I also dive into advanced topics such as named captures, look ahead and look behind. If you are a Pluralsight subscriber, I hope you'll add the course to your playlist. In the meantime, I'm sure I'll have more blog content this year that includes regular expressions.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

3 thoughts on “Learn More about PowerShell and Regular Expressions”

  1. Thomas Lee says:
    February 7, 2020 at 5:56 am

    Great article – and i LOVE the GitStat function. I have ‘stolen’ it and am using it.

    I’ve added in some error handling (to cater for no files to add/commit, and need to update to recognise unpushed updates. but definitely a keeper!

    Thanks

  2. Pingback: ICYMI: PowerShell Week of 07-February-2020 | PowerShell.org
  3. PvtSkidmark says:
    February 9, 2020 at 11:23 am

    Appreciate the example and the mention of your Pluralsight course, which I just bookmarked. Just a couple of days ago, I was trying to figure out a Regex and got mixed up with “.” and “+”.

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d