If you’ve ever needed to extract specific information from a log file or validate user input in a PowerShell script, you’ve probably wished for a magic tool that could do the heavy lifting. Well, that’s exactly where regular expressions (regex) come in.

Regex is one of those tools that feels intimidating at first, but once you get the hang of it, you’ll start seeing patterns everywhere. It’s like suddenly being able to read the Matrix, except instead of dodging bullets, you’re filtering out bad email addresses or pulling MAC addresses from a system log.

Why Use Regex in PowerShell?

PowerShell has built-in support for regex, making it an incredibly powerful tool for system administrators, developers, and anyone who works with structured or unstructured text. Whether you’re:

  • Validating user input (like email addresses in a script)
  • Extracting important data from logs (like MAC or IP addresses)
  • Searching for patterns in massive amounts of text

Regex allows you to do all of this with just a few carefully crafted expressions. It’s like having a Swiss Army knife for text processing.

What We’ll Cover in This Guide

In this post, we’ll walk through three practical PowerShell regex use cases:

  1. Email Addresses – How to validate email input and extract emails from a document
  2. MAC Addresses – How to validate MAC addresses and find them in logs
  3. IP Addresses – How to check if an IP is valid and pull all IPs from a file

Before we dive into these examples, we’ll go over some regex basics, including common syntax and flags that make regex so powerful. By the end, you’ll not only understand how regex works in PowerShell but also feel confident using it in your own projects.

Let’s get started!

Understanding Regex Flags and Syntax

Regular expressions might look like a confusing mess of symbols at first, kind of like trying to understand a cat’s behavior. One minute it’s purring in your lap, the next it’s knocking your coffee off the table. But once you start recognizing the patterns—like how a tail flick means back away, human—it all starts to make sense.

Regex is the same way. At first glance, it looks like a secret code of slashes, dots, and brackets. But once you learn the building blocks, you start seeing patterns everywhere, and suddenly, text manipulation in PowerShell becomes effortless. PowerShell has native support for regex, meaning you can use it to search, validate, and extract information with just a few well-placed symbols—kind of like bribing a cat with treats to do what you want.

Character Classes: Defining What to Match

Character classes allow you to specify what kind of characters should match. Instead of listing every possibility, regex provides shorthand notations.

Common Character Classes in PowerShell Regex

Character ClassDescriptionExample Match
\dMatches any digit (0-9)123 in abc123
\wMatches any word character (A-Z, a-z, 0-9, _)hello in hello_123
\sMatches any whitespace (space, tab, newline)The space in "Hello World"
.Matches any character (except newline)H or ! in "Hi!"

Example in Powershell:

"This is a test 123" -match "\d+"  # Matches "123"

Quantifiers: Controlling Repetitions

Quantifiers define how many times a pattern should repeat.

Common Quantifiers

QuantifierDescriptionExample Match
*Matches 0 or more timesaaa in "aaaaa"
+Matches 1 or more timesabc in "abc"
?Matches 0 or 1 time (optional)a in "a" or empty string
{n}Matches exactly n times333 in "333"
{n,}Matches at least n times111 in "11111"
{n,m}Matches between n and m times55 in "5555" (if {2,3})

Example in PowerShell:

"This is 55555" -match "\d{2,3}"  # Matches "555"

Anchors: Defining Position in Text

Anchors don’t match actual characters but instead define where a match should occur.

Common Anchors

AnchorDescriptionExample Match
^Matches the start of a stringHello in "Hello world"
$Matches the end of a stringworld in "Hello world"
\bMatches a word boundarycat in "cat dog" but not "scatter"

Example in PowerShell:

"This is a test" -match "^This"  # Matches "This"

Escaping Special Characters

Some characters in regex have special meanings (like . or *). If you want to match them literally, you need to escape them with a backslash \.

Common Special Characters That Need Escaping

  • . (dot) → Matches any character, so use \. to match a literal dot.
  • * (asterisk) → Use \* to match an actual asterisk.
  • ? (question mark) → Use \? to match a literal question mark.

Example in PowerShell:

"This is version 1.0.1" -match "1\.0\.1"  # Matches "1.0.1"

How to Use Regex in PowerShell

PowerShell provides multiple ways to work with regex:

  1. -match Operator – Checks if a string matches a pattern.
  2. -replace Operator – Replaces matched patterns in a string.
  3. [regex]::matches() – Extracts all matches from a string.

Example of Finding All Matches in a String:

$text = "Emails: test@example.com, admin@company.net"
$pattern = "[\w\.-]+@[\w\.-]+\.\w+"
$matches = [regex]::Matches($text, $pattern)

$matches.Value  # Outputs: test@example.com, admin@company.net

Extracting and Validating Email Addresses with PowerShell

When working with PowerShell scripts, validating user input is crucial—especially when dealing with email addresses. You don’t want users submitting "notanemail@oops" or "hello@.com" and breaking your workflow. Thankfully, regex makes it easy to verify if an email address is properly formatted and even extract all emails from a document.

Before we get into validating and extracting emails, let’s break down the regex pattern that makes it all work.

Breaking Down the Email Regex

Email validation might seem simple at first—just look for an “@” symbol, right? But things get complicated fast. A valid email address follows these rules:

  1. A username section, which can include letters, numbers, dots, dashes, and underscores.
  2. An “@” symbol separating the username from the domain.
  3. A domain name that includes letters and numbers.
  4. A top-level domain (TLD) like .com, .net, .org, etc.

A regex pattern that matches most valid email addresses looks like this:

[\w\.-]+@[\w\.-]+\.\w+

Let’s break it down piece by piece:

Username Section: [\w\.-]+

  • \w → Matches letters, numbers, and underscores (a-z, A-Z, 0-9, _).
  • . and - → Allows dots and dashes in the username.
  • + → Ensures one or more of these characters exist.

“@” Symbol: @

  • The @ is a literal character—every valid email must have it.

Domain Name: [\w\.-]+

  • Just like the username, the domain allows letters, numbers, dots, and dashes.

Top-Level Domain (TLD): \.\w+

  • \. → Matches a literal dot before the TLD.
  • \w+ → Ensures at least one letter (like .com or .net).

Example Matches:

  • user@example.com
  • john.doe123@company.co.uk
  • admin-test@my-site.net

Invalid Matches:

  • @example.com (No username)
  • user@.com (Invalid domain name)
  • user@domain (No TLD)

This regex is great for general email validation, but in PowerShell, we need to apply it properly. Next, we’ll use this pattern in a ValidateSet to enforce correct email input in scripts.

Using Regex for PowerShell ValidateSet

PowerShell has built-in ways to enforce valid input in scripts, and one way to do this is by using regex inside a function. The function below checks if an email matches our regex pattern. If it’s valid, it returns $true; if not, it gives a reason why.

PowerShell Email Validation Function

function Test-EmailAddress {
    param (
        [string]$Email
    )

    $pattern = "^[\w\.-]+@[\w\.-]+\.\w+$"

    if (-not $Email) {
        return "False - No email provided."
    }

    if ($Email -match $pattern) {
        return "True"
    }
    
    # Now let's figure out why it failed  
    if ($Email -notmatch "@") {
        return "False - Missing '@' symbol."
    }
    
    if ($Email -match "@\." -or $Email -match "@$") {
        return "False - Invalid placement of '@' or '.'"
    }

    if ($Email -notmatch "\.\w+$") {
        return "False - Missing top-level domain (e.g., .com, .net)."
    }

    return "False - Invalid email format."
}

How It Works

  1. Checks if an email is provided – If the input is empty, it immediately returns a failure message.
  2. Validates using regex – If the input matches the regex pattern, it returns True.
  3. Identifies why the email is invalid – It checks for common issues like missing @, misplaced dots, or a missing TLD.

This function is useful for scripts that require valid emails before proceeding. Next, we’ll explore how to extract all emails from a document using regex!

Finding All Email Addresses in a Document

If you’re working with logs, reports, or any large text files, regex is your best friend for extracting structured data like email addresses. Instead of manually scanning through lines of text, PowerShell can do the heavy lifting in seconds.

Here’s a script that:

  1. Reads a file line by line.
  2. Uses regex to find all email addresses.
  3. Outputs the results to the console (or optionally saves them to another file).

PowerShell Script to Extract Emails from a File

function Get-EmailAddressesFromFile {
    param (
        [string]$FilePath
    )

    if (-not (Test-Path $FilePath)) {
        Write-Host "Error: File not found at path: $FilePath"
        return
    }

    $pattern = "[\w\.-]+@[\w\.-]+\.\w+"
    $emails = @()

    Get-Content $FilePath | ForEach-Object {
        $matches = [regex]::Matches($_, $pattern)
        if ($matches.Count -gt 0) {
            $emails += $matches.Value
        }
    }

    if ($emails.Count -eq 0) {
        Write-Host "No email addresses found in the file."
    } else {
        Write-Host "Found $($emails.Count) email addresses:"
        $emails | Sort-Object -Unique
    }
}

# **Example Usage**
Get-EmailAddressesFromFile -FilePath "C:\path\to\your\file.txt"

How It Works

  1. Checks if the file exists – Avoids errors if the file path is incorrect.
  2. Reads the file line by line – Prevents loading large files into memory at once.
  3. Uses regex to find emails – Looks for matches in each line.
  4. Stores and displays unique results – Avoids duplicates and outputs all found emails.

Example File (C:\path\to\your\file.txt)

Hello John, please contact us at support@example.com.
You can also reach admin@company.net for further assistance.
But we dont want to see a snail@the white house. 
However, we might @ your friend .com
How about a cheesecake@cheesecakefactory.com?

Script Output

Found 3 email addresses:
admin@company.net
cheesecake@cheesecakefactory.com
support@example.com

This script is super useful for extracting emails from logs, reports, or even messy text files. Next up, we’ll apply these same techniques to MAC addresses!

Extracting and Validating MAC Addresses with PowerShell

MAC addresses (Media Access Control addresses) are unique hardware identifiers assigned to network interfaces. If you’re dealing with network logs, device configurations, or security audits, you may need to validate or extract MAC addresses.

A valid MAC address follows one of these formats:

  • Colon-separated: 00:1A:2B:3C:4D:5E
  • Hyphen-separated: 00-1A-2B-3C-4D-5E
  • No separator: 001A2B3C4D5E

But Cisco devices often use a dot-separated format:

  • Cisco-style: 001A.2B3C.4D5E

Now, let’s break down the regex pattern that will help us match MAC addresses.

Breaking Down the MAC Address Regex

MAC addresses consist of six groups of two hexadecimal digits (0-9 and A-F), separated by colons, hyphens, or nothing at all. Here’s a regex pattern that matches all common formats:

([A-Fa-f0-9]{2}[:-]?){5}[A-Fa-f0-9]{2}|([A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4}

Breaking It Down

  1. First Half: Standard MAC Formats
    • ([A-Fa-f0-9]{2}[:-]?){5}[A-Fa-f0-9]{2} → Matches colon, hyphen, or no separator formats.
  2. Second Half: Cisco’s Dot-Format
    • ([A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4} → Matches two groups of four hex digits separated by dots.

Example Matches:

  • 00:1A:2B:3C:4D:5E
  • 00-1A-2B-3C-4D-5E
  • 001A2B3C4D5E
  • 001A.2B3C.4D5E (Cisco format!)

Invalid Matches:

  • 00:1A:2B:3C:4D (Only five pairs)
  • 00:1G:2B:3C:4D:5E (Invalid hex digit G)
  • 00::1A:2B:3C:4D:5E (Double colon is not valid)

Using Regex for PowerShell ValidateSet (Including Cisco Format)

We’ll now create a PowerShell function that checks if a given MAC address is valid. If it’s valid, it returns True; if not, it returns False with a reason why.

Updated PowerShell MAC Address Validation Function

function Test-MacAddress {
    param (
        [string]$MacAddress
    )

    $pattern = "^([A-Fa-f0-9]{2}[:-]?){5}[A-Fa-f0-9]{2}$|^([A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4}$"

    if (-not $MacAddress) {
        return "False - No MAC address provided."
    }

    if ($MacAddress -match $pattern) {
        return "True"
    }

    # Identify why it failed
    if ($MacAddress -notmatch "^[A-Fa-f0-9]+$" -and $MacAddress -notmatch "[:-\.]") {
        return "False - Contains invalid characters."
    }

    if ($MacAddress -notmatch "([A-Fa-f0-9]{2}[:-]?){5}[A-Fa-f0-9]{2}" -and $MacAddress -notmatch "([A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4}") {
        return "False - Incorrect format. Should be XX:XX:XX:XX:XX:XX, XX-XX-XX-XX-XX-XX, XXXXXXXX, or XXXX.XXXX.XXXX (Cisco)."
    }

    return "False - Invalid MAC address format."
}

How It Works

  1. Checks if a MAC address is provided – Ensures input isn’t empty.
  2. Uses regex for validation – If the input matches the pattern, it’s valid.
  3. Identifies specific errors – Helps users understand why an input is invalid.

Now that we can validate a single MAC address, let’s move on to extracting all MAC addresses from a file!

Finding All MAC Addresses in a Document

This next script scans a file and extracts all MAC addresses using regex. It works just like our email extraction script, but with a MAC address pattern.

PowerShell Script to Extract MAC Addresses from a File

function Get-MacAddressesFromFile {
    param (
        [string]$FilePath
    )

    if (-not (Test-Path $FilePath)) {
        Write-Host "Error: File not found at path: $FilePath"
        return
    }

    $pattern = "([A-Fa-f0-9]{2}[:-]?){5}[A-Fa-f0-9]{2}|([A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4}"
    $macAddresses = @()

    Get-Content $FilePath | ForEach-Object {
        $matches = [regex]::Matches($_, $pattern)
        if ($matches.Count -gt 0) {
            $macAddresses += $matches.Value
        }
    }

    if ($macAddresses.Count -eq 0) {
        Write-Host "No MAC addresses found in the file."
    } else {
        Write-Host "Found $($macAddresses.Count) MAC addresses:"
        $macAddresses | Sort-Object -Unique
    }
}

# **Example Usage**
Get-MacAddressesFromFile -FilePath "C:\path\to\your\file.txt"

How It Works

  1. Checks if the file exists – Prevents errors if the file path is wrong.
  2. Reads the file line by line – Efficient for large files.
  3. Uses regex to extract MAC addresses – Searches each line for matches.
  4. Stores and displays unique results – Removes duplicate addresses for cleaner output.

Example File (C:\path\to\your\file.txt)

Device 1: 00:1A:2B:3C:4D:5E  
Device 2: 00-1A-2B-3C-4D-5E  
Cisco Router: 001A.2B3C.4D5E  
Error Log: Invalid MAC -> 00:1A:2B:3G:4D:5E  

Script Output

Found 3 MAC addresses:
00:1A:2B:3C:4D:5E
00-1A-2B-3C-4D-5E
001A.2B3C.4D5E

This script is super useful for network admins who need to extract MAC addresses from logs or reports. Next up, we’ll do the same for IP addresses!

Extracting and Validating IP Addresses with PowerShell

IP addresses are everywhere—logs, configs, audit reports—you name it. If you’re working with networking or security, you’ll often need to validate or extract IPs from text files.

We’re going to cover IPv4 and IPv6, because while IPv4 is still dominant, IPv6 is becoming more common.

What Makes an IP Address Valid?

IPv4 Format

  • Consists of four octets (groups of numbers) separated by dots: 192.168.1.1
  • Each octet must be between 0 and 255

IPv6 Format

  • Consists of eight groups of hexadecimal numbers (0-9, A-F), separated by colons: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
  • Can contain compressed notation (e.g., :: represents consecutive zero blocks)

Breaking Down the IP Address Regex

To match both IPv4 and IPv6, we’ll use two separate regex patterns.

IPv4 Regex Pattern

\b((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\b

Breaking It Down

  • 25[0-5] → Matches 250-255
  • 2[0-4][0-9] → Matches 200-249
  • 1[0-9]{2} → Matches 100-199
  • [1-9]?[0-9] → Matches 0-99
  • \. → Ensures each octet is separated by a dot
  • {3} → Ensures exactly three dots appear

IPv6 Regex Pattern

\b([A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}\b

Breaking It Down

  • [A-Fa-f0-9]{1,4} → Matches hexadecimal numbers (1-4 digits)
  • : → Ensures each section is separated by a colon
  • {7} → Ensures exactly seven colons appear

⚠️ This regex does not handle compressed IPv6 addresses (::), but we’ll take care of that in PowerShell logic!

Using Regex for PowerShell ValidateSet

Now, let’s create a PowerShell function to validate both IPv4 and IPv6 addresses.

PowerShell IP Address Validation Function

function Test-IPAddress {
    param (
        [string]$IPAddress
    )

    $ipv4Pattern = "^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$"
    $ipv6Pattern = "^([A-Fa-f0-9]{1,4}:){7}[A-Fa-f0-9]{1,4}$"

    if (-not $IPAddress) {
        return "False - No IP address provided."
    }

    if ($IPAddress -match $ipv4Pattern) {
        return "True (IPv4)"
    }

    if ($IPAddress -match $ipv6Pattern -or $IPAddress -match "^(::|([A-Fa-f0-9]{1,4}:){1,6}:?([A-Fa-f0-9]{1,4})?)$") {
        return "True (IPv6)"
    }

    return "False - Invalid IP address format."
}

How It Works

  1. Checks for input – Ensures an IP address was provided.
  2. Matches against IPv4 regex – If valid, returns True (IPv4).
  3. Matches against IPv6 regex – If valid, returns True (IPv6).
  4. Handles compressed IPv6 (::) – Using additional PowerShell logic.
  5. Returns an error if invalid – Helps troubleshoot incorrect formats.

Now, let’s move on to extracting all IPs from a document!

Finding All IP Addresses in a Document

This script scans a file and extracts all IPv4 and IPv6 addresses.

PowerShell Script to Extract IP Addresses from a File

function Get-IPAddressesFromFile {
    param (
        [string]$FilePath
    )

    if (-not (Test-Path $FilePath)) {
        Write-Host "Error: File not found at path: $FilePath"
        return
    }

    $ipv4Pattern = "\b((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\b"
    $ipv6Pattern = "\b([A-Fa-f0-9]{1,4}:){1,7}[A-Fa-f0-9]{1,4}\b"
    $ipAddresses = @()

    Get-Content $FilePath | ForEach-Object {
        $matchesIPv4 = [regex]::Matches($_, $ipv4Pattern)
        $matchesIPv6 = [regex]::Matches($_, $ipv6Pattern)

        if ($matchesIPv4.Count -gt 0) {
            $ipAddresses += $matchesIPv4.Value
        }
        if ($matchesIPv6.Count -gt 0) {
            $ipAddresses += $matchesIPv6.Value
        }
    }

    if ($ipAddresses.Count -eq 0) {
        Write-Host "No IP addresses found in the file."
    } else {
        Write-Host "Found $($ipAddresses.Count) IP addresses:"
        $ipAddresses | Sort-Object -Unique
    }
}

Example File (C:\path\to\your\file.txt)

Server 1: 192.168.1.1  
Server 2: 255.255.255.255  
Router: 2001:db8:85a3::8a2e:370:7334  
Log Entry: Invalid IP -> 999.999.999.999  

Script Output

Found 3 IP addresses:
192.168.1.1
255.255.255.255
2001:db8:85a3::8a2e:370:7334

Regex Exploration in PowerShell

At this point, you’ve seen how regex can validate, extract, and manipulate data in PowerShell. Whether it’s emails, MAC addresses (including Cisco formats), or IPs (both IPv4 and IPv6), you now have practical tools to handle real-world scenarios.

Why Keep Learning Regex?

Regex is one of those skills that pays off the more you use it. The same way a system admin gets better at troubleshooting networks over time, you’ll get faster at spotting patterns and writing efficient expressions.

Here are some great ways to keep sharpening your regex skills:

  • Practice on Real Logs – Take a firewall log, an Apache log, or an email report and extract useful data.
  • Use Online Regex Tools – Websites like regex101.com let you test regex patterns with real-time explanations.
  • Experiment with PowerShell – Try using -match, -replace, and [regex]::Matches() in your daily scripts.
  • Challenge Yourself – Create a script that finds phone numbers, dates, or even URLs in a document.
  • Accept Growth – A few years ago, I wrote SHD – Set Mac Structure – The Random Admin, and I am glad to say I have grown a lot since then. It feels good.

Final Thought

Regex is a skill, not magic. It may look complex at first, but like learning any new language, it becomes second nature with practice. The best way to improve? Find a problem and solve it with regex.

So, what’s your next PowerShell regex use case going to be?

What can we learn as a person today?

When a script fails, we don’t just throw our hands up and quit—we debug it. We check the logs, isolate the issue, and find a fix. But when our own minds start feeling overwhelmed, anxious, or burned out, we often just push through, hoping the problem resolves itself. What if we approached our mental health like we approach troubleshooting code? Debugging isn’t just for PowerShell scripts—it can work for stress, too.

Find the errors

The first step in debugging stress is identifying the error messages. In IT, a recurring issue in the logs might mean something deeper is wrong, and the same goes for mental health. Are you feeling exhausted every morning? Snapping at coworkers over small things? Losing focus even on tasks you usually enjoy? These could be your mind’s version of Event ID 1000: Application Crash. Instead of ignoring the warning signs, acknowledge them—just like you would in a system check.

Analyze the variables

Next, we analyze the variables. Just like a misconfigured setting can break a script, small changes in your routine can make or break your mental well-being. Are you sleeping enough? Eating well? Taking breaks? IT professionals are notorious for skipping meals, working through exhaustion, and staying up late chasing down problems. But just like an unstable system needs a reboot, your brain needs rest. Run a self-check—what’s missing from your routine that could improve stability?

Implement something

Finally, implement a fix and test the results. Maybe you start with a simple -replace—swapping out caffeine overload for proper hydration or scheduling actual breaks instead of “just five more minutes.” Maybe you automate self-care reminders, like setting a PowerShell script to remind you every hour to step away from the screen. And if the issue persists? Just like with a stubborn bug, escalate it—talk to a friend, mentor, or even a therapist. There’s no shame in calling in extra support when needed.

In IT, we don’t assume things will “just work”—we test, refine, and optimize. Treat your mental health the same way. Debug your stress, adjust your variables, and don’t be afraid to run an upgrade on your self-care routine. The best systems run smoothly when properly maintained—and that includes you.