LaPhi
LaPhi

Reputation: 5897

Count specific strings with wildcard

How can I count specific strings in a text file with PowerShell? (I know how I can count normal specific strings)

My plan is to count domain accounts in a log file. The script has to search for "Domain*" but how can I do it?

Example Source Data:

Test request Domain\User1 Test Request Domain\User1 Test Request Test Domain\User2 Test

Excepted result:

Upvotes: 1

Views: 204

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

I would use a regex to capture all users and use the Select-Object cmdlet with the -unique switch to get a unique list:

$yourString = 'Test request Domain\User1 Test Request Domain\User1 Test Request Test Domain\User2 Test'
$result = @([regex]::Matches($yourString, 'Domain\\([\S]+)') | ForEach-Object { $_.Groups[1].Value } | select -Unique)
Write-Host "Found $($result.count) User"
Write-Host "$($result -join ' and ')"

Output:

Found 2 User
User1 and User2

Upvotes: 2

Related Questions