Find the signal in a log
Match log entries and extract an IPv4-looking string.
Match text deliberately
-like uses wildcards, while -match uses a regular expression. A regular expression describes a text pattern.
'FAILED user=ada ip=192.0.2.10' -match 'FAILED'
For a single input string, a successful -match also fills $Matches. $Matches[0] contains the whole match. Named capture groups give important parts a readable name:
$line = 'FAILED user=ada ip=192.0.2.10'
if ($line -match 'ip=(?<address>\d+\.\d+\.\d+\.\d+)') {
$Matches.address
}
Read $Matches only after the match succeeds; an unsuccessful match may leave earlier values there.
Extract, then deduplicate
Select-Object -Unique removes repeated values. You can collect results from a loop and pipe them to that cmdlet.
The simple pattern above extracts the fixture's address format. It does not validate IPv4 ranges. Distinguish extracting a known format from validating arbitrary input.
The supplied log uses documentation-only addresses and contains no live network activity.
Get-Content './activity.log'Put it into practice.
Extract the ip= addresses from FAILED lines in activity.log. Output each failed address once, with no ip= prefix. Ignore OK lines.
See an explained solution
$addresses = foreach ($line in Get-Content './activity.log') {
if ($line -match '^FAILED .*ip=(?<address>\d+\.\d+\.\d+\.\d+)') {
$Matches.address
}
}
$addresses | Select-Object -UniqueThe named group extracts addresses from failed events. Deduplication produces two values even though one address occurs twice.