Search code examples
powershellcounterfind-replace

How to count successful find (and replace)


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...


Solution

  • 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 ...