0
0
PowerShellscripting~30 mins

Regex quantifiers and anchors in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
Regex quantifiers and anchors in PowerShell
📖 Scenario: You work in IT support and need to filter log entries to find specific patterns. Logs contain timestamps and messages. You want to find lines that start with a date and time, and contain a specific word repeated a certain number of times.
🎯 Goal: Build a PowerShell script that uses regex quantifiers and anchors to match log lines starting with a date and time, and containing a repeated word pattern.
📋 What You'll Learn
Create a variable $logLines with 3 exact log entries
Create a variable $pattern with a regex pattern using anchors and quantifiers
Use Where-Object with -match operator and $pattern to filter matching lines
Print the matching lines using Write-Output
💡 Why This Matters
🌍 Real World
Filtering log files to find specific error patterns helps IT support quickly identify issues.
💼 Career
Regex skills are essential for scripting and automation tasks in system administration and data processing.
Progress0 / 4 steps
1
Create the log lines data
Create a variable called $logLines and assign it an array with these exact strings: '2024-06-01 10:00:00 INFO Start process', '2024-06-01 10:05:00 ERROR Error Error Error occurred', and '2024-06-01 10:10:00 INFO End process'.
PowerShell
Need a hint?

Use @( ... ) to create an array in PowerShell.

2
Create the regex pattern with anchors and quantifiers
Create a variable called $pattern and assign it a regex string that matches lines starting with a date and time in the format YYYY-MM-DD HH:MM:SS (use ^ anchor), followed by a space, then the word ERROR, then a space, then the word Error repeated exactly 3 times separated by spaces, using quantifiers, and then any text after.
PowerShell
Need a hint?

Use ^ to anchor start, \d{4} for 4 digits, and (Error ){3} to repeat 'Error ' exactly 3 times.

3
Filter log lines using the regex pattern
Use Where-Object with -match operator and the variable $pattern to filter $logLines for matching lines. Store the result in a variable called $matchingLines.
PowerShell
Need a hint?

Use $matchingLines = $logLines | Where-Object { $_ -match $pattern } to filter.

4
Print the matching log lines
Use Write-Output to print the variable $matchingLines.
PowerShell
Need a hint?

Use Write-Output $matchingLines to display the filtered lines.