Getting Started with PowerShell and Regex

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is Microsoft’s powerful scripting environment for Windows. It opens up a plethora of possibilities, from automating administrative tasks to creating your own tools. PowerShell provides several built-in functions that can be leveraged by using regular expressions in order to create customizable commands and scripts.

Getting Started with PowerShell and Regex

PowerShell is a command-line tool that allows users to perform complex tasks with ease. In this article, we will learn how to use PowerShell to replace text within a string and also how to use regular expressions.

Regular expressions (regex) might be difficult for us, humans, to grasp, yet regex can be a very effective technique to interact with text. You’ll learn the fundamentals of dealing with regex and PowerShell in this tutorial.

You’ll learn about regex capture groups and different regex parsing approaches, as well as gain an introduction to useful cmdlets like Select-String.

Prerequisites

  • PowerShell 5.1+ on a Windows 7 or later computer. PowerShell 7.1.0 will be used in this tutorial.

Using Select-String to Match Simple Text

It’s usually ideal to go through a real example when demonstrating PowerShell and regex together.

Let’s imagine you’re collecting information on older computers’ hardware and using the wmic program to create a simple text file like the one below. It’ll be known as computername.txt.

BiosCharacteristics={7,11,12,15,16,19,20,21,22,23,24,25,27,30,32,33,39,40,42,43} BIOSVersion=”ACRSYS – 2″,”V1.15″,”INSYDE Corp. – 59040115″ BIOSVersion=”ACRSYS – 2″,”V1.15″,”INSYDE Corp. – 59040115″ BIOSVersion=”ACRSYS – 2″,” Caption=V1.15 BuildNumber= CurrentLanguage= CodeSet= EmbeddedControllerMajorVersion=1 Description=V1.15 EmbeddedControllerMinorVersion=15 InstallableLanguages= InstallDate= LanguageEdition= ListOfLanguages= IdentificationCode= Name=V1.15 Manufacturer=Insyde Corp. PrimaryBIOS=TRUE OtherTargetOS= ReleaseDate=20200826000000.000000+000 SerialNumber=NXHHYSA4241943017724S00 SMBIOSBIOSVersion=V1.15 SMBIOSMajorVersion=3 SMBIOSMinorVersion=2 SMBIOSPresent=TRUE SoftwareElementID=V1.15 SoftwareElementState=3 SoftwareElementID=V1.15 SoftwareElementState=3 Status=OK SystemBiosMajorVersion=1 TargetOperatingSystem=0 SystemBiosMinorVersion=15 Version=ACRSYS – Version=ACRSYS – Version=ACRSYS – Version=

Let’s pretend you need to retrieve the computer’s serial number in this case. The SerialNumber= line contains this serial number.

Select-String will become your new favorite tool in this circumstance.

Select-String is a PowerShell cmdlet that takes a regular expression pattern as an argument and returns a string that matches it.

How to use the Grep command in PowerShell (Select-String)

You’ll need to read the file first and then check for a regex match since the pattern you’re looking for is in a file. To do so, use the Pattern argument to provide a regex pattern and the Path option of specify the path to the text file.

Select-String -Pattern “SerialNumber” -Path “.computername.txt” Select-String -Pattern “SerialNumber” -Path “.computername.txt”

The Select-String cmdlet looks through the.computername.txt file for characters that match SerialNumber.

a select-string output examplea select-string output example

Regex, believe it or not, is something you’re already familiar with. Regex, in its most basic form, is a character matcher. You’re matching the actual “SerialNumber” phrase in this case.

However, you are unlikely to desire the whole line. Instead, let’s start writing a native script to fetch just the data you’re interested in.

Output from Select-String is a Rich Object.

Select-String produced what seemed to be a simple string in the preceding example, but the result was really a lot more. Select-String returns more than simply a text match. The cmdlet returns a complete object.

For example, to search in the string This is a string, give a regex pattern of This (is). Select-String produces a Microsoft.PowerShell.Commands.MatchInfo object if you feed that output to Get-Member, as seen below.

“This (is)” is a select-string. | get-member -inputobject “This is a String”

A select-string operation's attributesA select-string operation’s attributes

Capture Groups in Action

Take note of the regex pattern used in the preceding example (This (is)). A set of parentheses is used in this design. Those parentheses form a capture group in a regular expression.

PowerShell creates a capture group by enclosing a search word in parentheses. The content of a regex search is “captured” into a variable using capture groups.

Select-String produces a property named Matches in the example above. All lines or values of capture groups (if employing parenthesis) detected are stored in this property.

All capture group values may be found in the Matches section. Property for groups. The value property of the groups property is the actual data, which is contained inside an array of objects. The groups array is incremented by each capture group you provide in the Regex term, starting at 0 (with the value of the whole regex match).

With the matches property, you can extract both the whole string and the is match you extracted in the previous example:

select-string $match “This (is)” says the speaker. #this property will match the whole select-string value $match. -inputobject “This is a String” Matches.groups[0].value #The first capture group $match will be matched by this property. Matches.groups[1].value

1647499971_620_Getting-Started-with-PowerShell-and-Regexthe result of a capture group’s work

Capture Groups in Action with Pattern Matches

Similarly to catching the literal is in, capturing a literal string is very meaningless. This is the case. You’re not getting any useful information by collecting a string whose contents you already know. You may also use a combination of capture groups and pattern matching to retrieve just the data you need.

Rather to matching a single character, pattern matching uses specifically specified characters to match a range of characters. Pattern matching is similar to a wildcard * (like in notepad) on steroids.

Consider the case when you simply want to match the serial number in the line SerialNumber=NXHHYSA4241943017724S00 and not the complete line. You want to take a screenshot of any character after the SerialNumber= sentence. Using the special dot. character, followed by a regex wildcard *, you can extract that pattern (referred to as a Quantifier).

After SerialNumber=, the dot instructs regex to match any single character. The * instructs regex to repeat the. match a certain number of times. The regex will appear like SerialNumber=(.*) when used with a capture group. This is what you’ll see below:

#retrieve the serial number using a capture group $string = “SerialNumber=numberwecareabout1042” $match = select-string “SerialNumber=(.*)” $match = select-string “SerialNumber=(.*)” -inputobject #output the serial number as a string $match.matches.groups[1].value

Capture Groups in Action to extract important informationCapture Groups in Action to extract important information

The special. character is only one of several pattern match options available. Words, character ranges, numeric ranges, and other things may be matched. The Regex Reference category on the regexr website (accessed through the sidebar) is a great place to learn about various regex expressions.

An Example of a PowerShell Regex

Let’s put all of this together to make a script that:

  1. A list of text files is ingested (in the example, you will only grab the sample text file)
  2. SerialNumber=(.*) loops over the text files to get the serial number.
  3. This function creates a hashtable using a list of machine names and serial numbers.

#Make a hashtable to keep track of the serial numbers. @$serialNumbers$serialNumbers$serialNumbers$serialN # Take a look at all of the text files. You’re restricting your scope to a single text file in this scenario. $files = Get-ChildItem “$pwdcomputername.txt” #foreach ($file in $files) fill the hashtable #First, like in the first example, obtain the same string. $serialNumber = select-string “SerialNumber=(.*)” $file $serialNumber = select-string “SerialNumber=(.*)” $file $serialNumber = select-string “SerialNumber=(.*)” $file FullName #Now, solely retrieve the serial number using the capture group. The special matches property is used to do this. We also use the filename (without the suffix) as the serial number index. $serialNumbers[$file.basename] = $serialNumber.matches.groups[1].value $serialNumbers[$file.basename] = $serialNumber.matches.groups[1].value $serialNumbers[$file. # print the hashtable’s output to the screen format-table | $serialNumbers

Using computername.txt, you can see the aforementioned script in action:

the output of the preceding codethe output of the preceding code

The Operator for Matching

You’ve learned how to match regex patterns in text using Select-String, but PowerShell also provides a few useful regex operators.

The match and notmatch operators are two of the most useful and common PowerShell regex operators. You may use these operators to see whether a text has a given regex pattern.

If the string does match the pattern, The Operator for Matching will return a True value. If not, it will return a False value. The opposite is true for the notmatch operator.

You can see an example of this behavior in action in the video below.

“string is in my string!” if(“my string” -match “string”) “string is in my string!”

The Split Operator is a command that divides two objects into

If you’d like to split strings on non-static character like a space, a comma or a tab, you can use The Split Operator is a command that divides two objects into. The Split Operator is a command that divides two objects into performs a regex match on a string and take a second action of splitting the string into one or more strings.

The Split Operator is a command that divides two objects into “converts” a string into an array of strings split on a specific regex pattern.

#make a string array separated by the “” symbol. Because it is a special character, the “” is escaped inside split “someone once warned me the earth was going to roll me” -divide (“\”)

Validation of the ValidatePattern parameter

Regex support in PowerShell isn’t limited to cmdlets and operators; you can also use it to match regex in arguments.

Related: PowerShell Parameters: Everything You Needed to Know

Using the Validation of the ValidatePattern parameter attribute, you can validate string parameter values based on a regex pattern. This validation routine is useful to limit what input a user can use for a parameter value.

#sample of regex validation This function’s ValidatePattern only accepts lowercase and uppercase alphabetical letters, as well as spaces. The start of the string is represented by #the at the start of the regex, and the end of the string is represented by $ at the end (to match the *entire* string). The + #denotes that the string must include at least one character in order to be accepted. function param([ValidatePattern(‘[a-zA-Z]+

Using PowerShell and Regex to Replace Text

You learnt a few different techniques to match patterns using PowerShell and regex in the previous parts. You may take that understanding a step further by replacing text that PowerShell has matched.

The -replace operator is a common approach for replacing text using regex. The -replace operator accepts two parameters (separated by a comma) and replaces a string with a replacement using regex. -replace also supports capture groups, enabling you to search for a capture group and then replace it with the match.

For example, you may insert text to a serial number using -replace:

$string = “SerialNumber=numberwecareabout1042” $string = “SerialNumber=numberwecareabout1042” #add the year to the end of the serialnumber using $currentYear = “2020” $serialNumber = $string -replace “SerialNumber=(.*)”,”SerialNumber=’$1-$currentYear” $serialNumber = $string -replace “SerialNumber=(.*)”,”SerialNumber=’$1-$currentYear” write-output $serialNumber

Using the -replace operator to append text and capturing groupsUsing the -replace operator to append text and capturing groups

The dollar symbol in $1 is escaped using a backtick in the preceding example. PowerShell would otherwise consider $1 as a variable rather than a special regex character.

Getting Better at Writing PowerShell Regex

All of the foregoing may seem to be difficult, and it is. There are a lot of regex features that aren’t included in the example above. Regex is a frequently used way of machine reading, and there are several tools available to assist in learning how to utilize it efficiently.

  • RegexOne is widely regarded as the de facto resource for regex learning. Regexone is a bite-sized and interactive introduction to the possibilities of regex, allowing you to learn regex as you write it. RegexOne is an excellent place to start learning about regex from the beginning.
  • Regexr is one of the greatest tools for validating and creating regexes. Regexr contains a cheatsheet and a terrific documentation engine in addition to a great real-time regex testing tool.
  • The.Net engine is used by Regexstorm to power its tool. Although it lacks the bells and whistles of sites like Regexr, it will reliably test your regular expression in the same manner that PowerShell does. Even if you generate your regex with other tools, you should always run it using regexstorm to ensure that PowerShell parses it properly.

If you don’t have to, don’t use PowerShell with Regex!

PowerShell is a scripting language that deals with objects. Structured objects are at the heart of PowerShell. Objects with properties are much simpler to maintain than loose text, especially when regex is used.

Understanding PowerShell Objects (Back to Basics)

One of the primary goals of PowerShell, as well as structured languages like JSON, is to eliminate the need for regex and text processing. Regex is great for deciphering human language, but it’s something you should strive to avoid using while storing or sending data.

Wrangling REST APIs with PowerShell and JSON is a related article.

Regex on structured languages causes some individuals to get agitated.

Use an object-oriented technique or a structured language like JSON, XML, or other structured languages instead than regex! Even though regex can do just about anything, it doesn’t imply you should!

Now we’ll move on to Regex.

You should now have a rudimentary grasp of how regex aids computers in parsing and finding text, even when searching for very precise or intricate terms, after reading this article. In the context of PowerShell, you should also have the tools to test, validate, and learn about regex.

The RegexOne lessons are a great next step if you haven’t already. In PowerShell, put your regex skills to the test and improve your string skills!

)] alphaOnly write-output $alphaCharacters ([string]$alphaCharacters) This will be a success. #this will fail if alphaOnly “Hello Mom” is used. “Hello, Mom!” says alphaOnly.

Using PowerShell and Regex to Replace Text

You learnt a few different techniques to match patterns using PowerShell and regex in the previous parts. You may take that understanding a step further by replacing text that PowerShell has matched.

The -replace operator is a common approach for replacing text using regex. The -replace operator accepts two parameters (separated by a comma) and replaces a string with a replacement using regex. -replace also supports capture groups, enabling you to search for a capture group and then replace it with the match.

For example, you may insert text to a serial number using -replace:

$string = “SerialNumber=numberwecareabout1042” $string = “SerialNumber=numberwecareabout1042” #add the year to the end of the serialnumber using $currentYear = “2020” $serialNumber = $string -replace “SerialNumber=(.*)”,”SerialNumber=’$1-$currentYear” $serialNumber = $string -replace “SerialNumber=(.*)”,”SerialNumber=’$1-$currentYear” write-output $serialNumber

Using the -replace operator to append text and capturing groupsUsing the -replace operator to append text and capturing groups

The dollar symbol in $1 is escaped using a backtick in the preceding example. PowerShell would otherwise consider $1 as a variable rather than a special regex character.

Getting Better at Writing PowerShell Regex

All of the foregoing may seem to be difficult, and it is. There are a lot of regex features that aren’t included in the example above. Regex is a frequently used way of machine reading, and there are several tools available to assist in learning how to utilize it efficiently.

  • RegexOne is widely regarded as the de facto resource for regex learning. Regexone is a bite-sized and interactive introduction to the possibilities of regex, allowing you to learn regex as you write it. RegexOne is an excellent place to start learning about regex from the beginning.
  • Regexr is one of the greatest tools for validating and creating regexes. Regexr contains a cheatsheet and a terrific documentation engine in addition to a great real-time regex testing tool.
  • The.Net engine is used by Regexstorm to power its tool. Although it lacks the bells and whistles of sites like Regexr, it will reliably test your regular expression in the same manner that PowerShell does. Even if you generate your regex with other tools, you should always run it using regexstorm to ensure that PowerShell parses it properly.

If you don’t have to, don’t use PowerShell with Regex!

PowerShell is a scripting language that deals with objects. Structured objects are at the heart of PowerShell. Objects with properties are much simpler to maintain than loose text, especially when regex is used.

Understanding PowerShell Objects (Back to Basics)

One of the primary goals of PowerShell, as well as structured languages like JSON, is to eliminate the need for regex and text processing. Regex is great for deciphering human language, but it’s something you should strive to avoid using while storing or sending data.

Wrangling REST APIs with PowerShell and JSON is a related article.

Regex on structured languages causes some individuals to get agitated.

Use an object-oriented technique or a structured language like JSON, XML, or other structured languages instead than regex! Even though regex can do just about anything, it doesn’t imply you should!

Now we’ll move on to Regex.

You should now have a rudimentary grasp of how regex aids computers in parsing and finding text, even when searching for very precise or intricate terms, after reading this article. In the context of PowerShell, you should also have the tools to test, validate, and learn about regex.

The RegexOne lessons are a great next step if you haven’t already. In PowerShell, put your regex skills to the test and improve your string skills!

The “powershell regex starts with” is a very useful tool to use when you are trying to find a string of text in a file. The command will search through the text and let you know if it finds anything that matches your pattern.

Frequently Asked Questions

Can regex be used in PowerShell?

A: Regular expressions are a text-searching and pattern-matching language for finding patterns in strings of characters. A regular expression is composed of a set of rules, or symbols, that describe how to match certain patterns within the string.

What flavor of regex does PowerShell use?

A: PowerShell uses regular expressions, which are language-independent patterns that can be used to match text.

Which PowerShell operator will match a regular expression?

A: The -ci operator matches a regular expression.

Related Tags

  • powershell regex example
  • powershell select-string regex
  • powershell regex match groups
  • powershell regex extract
  • powershell regex cheat sheet

Table of Content