0

我正在尝试计算一个简单脚本进行的替换次数,如下所示:

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

替换完成得很好,但$count仍然在0...

4

2 回答 2

2

$count必须在要使用的函数内部或将其作为参数放置。

尝试这个

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
}
于 2017-09-07T13:49:38.120 回答
1

这是一个范围界定问题AFAIK $count不必先初始化。

增量逻辑看起来找到了。但是,您需要在增量后从函数中返回它。否则它仍然会0在函数之外的范围内定义。

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 ...
于 2017-09-07T13:58:17.227 回答