regex - Powershell select-string returns different values depending on number of matches -
i have report file generated , containes various file references. using select-string , regular expressions match on types of files , perform subsequent processing on them.
the dilemma have trying consistently identify number of matches when there 0 (0), 1 (1), or more 1 (2+) matches. here i've tried:
(select-string -path $outputfilepath -pattern $regex -allmatches).matches.count this return "null" if there 0 matches, "1" if 1 match, , "null" if more 1 match.
(select-string -path $outputfilepath -pattern $regex -allmatches).count this return "null" if there 0 or 1 match , number of matches if more 1 match.
i'm faily new powershell, trying find consistent way test on number of matches regardless of whether there 0, 1, or more 1 match.
try this:
$content = get-content $outputfilepath ($content -match $regex).count powershell has number of comparison operators make life easier. here's quick listing:
-eq -ne -gt -ge -lt -le -like -notlike -match -notmatch -contains -notcontains -in -notin -replace in instance, -match match $content string against regular expression $regex, , output grouped parenthesis. grouping collection of strings. can count objects , print out accurate count of matches.
so why doesn't code work expected? when have single match, .matches returns system.text.regularexpressions.match object looks string "test123":
groups : {test123} success : true captures : {test123} index : 15 length : 7 value : test123 why happen? because microsoft.powershell.commands.matchinfo object select-string returns. can verify attempting other properties .filename on single-match output.
okay, why can't of our matches in 1 go? because multiple matches return multiple objects, have collection you're trying operate on. collection has different type, , doesn't understand .matches. no collection returned on 1 match, instead single object understand .matches is!
long story short: these aren't outputs you're looking for!
Comments
Post a Comment