Regular Expression PowerShell RegEx

Regular Expression PowerShell RegEx

Hello,

Regular Expression is a great concept that can be used by a lot of language. It allows you to recognize string patterns. This is the kind of feature that webmaster use to be sure that you enter your phone number or email address in the expected format.

PowerShell can also use RegEx, thanks to the -match and -Replace operators.

Get-Help About_Operators
Regular Expression PowerShell RegEx - Match Help

Regular Expression PowerShell RegEx – Match Help

Get-Help about_Comparison_Operators
Regular Expression PowerShell RegEx - Detailed Match Help

Regular Expression PowerShell RegEx – Detailed Match Help

Regular Expression PowerShell RegEx – Example

'OnlyLetters' -replace '[A-Z]','1'
Regular Expression PowerShell RegEx - Exemple

Regular Expression PowerShell – Example

This is a pretty simple example of letters replacement by number 1. We can do a lot more complex tasks like

Extract the CN from an Active Directory DistinguishedName

$(whoami /fqdn) -replace '^CN=([^,]+).+$','$1'
Regular Expression PowerShell RegEx - Extract CN from DistinguishedName

Regular Expression PowerShell – Extract CN from DistinguishedName

The more complex match you want to achieve, the more complicated/unreadable the regex will be. I use a very nice tool to help to test, validate and read the regex I use/wrote:

https://regex101.com/

Regular Expression PowerShell RegEx - RexEx101

Regular Expression PowerShell RegEx – RexEx101

This tool explain each step of the regex on his top right corner. This can be a great help if you found a regular expression on a website that you want to adapt to your own needs without rewriting all of it on your own.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.