How to count successful find (and replace)

463 views Asked by At

I'm trying to count the number of replacements made by a simple script like so:

$count = 0
Function findAndReplace($objFind, $FindText, $ReplaceWith) {
    $count += $objFind.Execute($FindText, $matchCase, $matchWholeWord, \`
             $matchWildCards, $matchSoundsLike, $matchAllWordForms, \`
             $forward, $findWrap, $format, $ReplaceWith, $replace)
}

The replacements are done alright, but $count remains at 0...

2

There are 2 answers

2
G42 On BEST ANSWER

This is a scoping issue. AFAIK $count does not have to be initialized first.

The increment logic looks find. However, you will need to return it from the function after the increments. Otherwise it will still be 0 as defined within the scope outside of the function.

Function findAndReplace($objFind, $FindText, $ReplaceWith) {
    $count += $objFind.Execute($FindText, $matchCase, $matchWholeWord, \`
             $matchWildCards, $matchSoundsLike, $matchAllWordForms, \`
             $forward, $findWrap, $format, $ReplaceWith, $replace)
    return $count;
}

$myCountOutSideFunctionScope = findAndReplace -objFind ... -FindText ... -ReplaceWith ...
0
ShanayL On

$count has to be inside of the function to be used or place it as a parameter.

Try this

Function findAndReplace($objFind, $FindText, $ReplaceWith) {
    $count = 0
    $replacementfound = $objFind.Execute($FindText, $matchCase, $matchWholeWord, \`
             $matchWildCards, $matchSoundsLike, $matchAllWordForms, \`
             $forward, $findWrap, $format, $ReplaceWith, $replace)

    if ($replacementfound -eq "True"){$count++}
    write-host $count
}