LaPhi LaPhi - 3 months ago 15
PowerShell Question

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:


  • Found 2 User

  • User1 and User2


Answer

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
Comments