If you look at the following question you will see a way to get PowerShell/Select-String
to use single line mode: Multiline regex to match config block
The problem you're facing is that by default a RegEx is usually applied per line of input. So your RegEx is only working on the first line that has Internal user ID
and Login name
.
What you need to do is to either remove the line breaks from your input or tell Select-String
to use single line mode. In both cases you should adjust your RegEx to not use \n
as it won't be needed. You could do it like this:
Login name:\s+(\w+)\s+.*?User status:\s+(ENABLED|DISABLED)
After this you either need adjust your input by e.g. running -replace '`n'
(notice as well that you should be using `n
within PowerShell) or you could use a modifier on the the input like stated in the question above. Your RegEx would change in that case to:
(?s)Login name:\s+(\w+)\s+.*?User status:\s+(ENABLED|DISABLED)
Even after all that you're not going to be finished just yet, Select-String
actually returns line for line of an input if you supply -Path
, so it's a good idea to read the whole file at once beforehand.
An example could be the following:
$fileContent = (Get-Content c:\users\ssfors\desktop\audit\user.rep) -join ''
$results = $fileContent | Select-String -pattern "Login name:\s+(\w+)\s+.*?User status:\s+(ENABLED|DISABLED)" -AllMatches
foreach($match in $results.Matches){
foreach($group in $match.Groups){
echo $group.Value
}
}
if($results.Matches.Count -eq 1 -and $results.Matches[0].Groups.Count -eq 3){
echo "User Name:", $results.Matches[0].Groups[1].Value;
echo "Status:", $results.Matches[0].Groups[2].Value;
}
Notice that the example doesn't use the single line modifier because it's not needed. It's reading the file and concatenating the lines using nothing as a delimiter.
-Path
parameter? In addition I'm not sure if PowerShell would match in single line mode by default. You could either try to remove line breaks with a simple replace or use a more complex RegEx statement/command that allows for single line mode matching.