0
$check = $args[1]
$numArgs = $($args.count)
$totMatch = 0
#reset variables for counting

for ( $i = 2; $i -lt $numArgs; $i++ )
{
    $file = $args[$i]
    if ( Test-Path $file ) {
    #echo "The input file was named $file" 
    $match = @(Select-String $check $file -AllMatches | Select -Expand Matches | Select -Expand Value).count
    echo "There were $match Matches in $file"
    echo "There were $match Matches in $file" >> Output.txt

    $totMatch = $totMatch + $match
    }
    else {
        echo "File $file does not exist"
        echo "File $file does not exist" >> Output.txt
    }
}
echo "Total Matches Found: $totMatch"

基本上我创建了一个快速应用程序来查找搜索的单词并检查文件中的实例,有人知道如何编辑它以将找到该单词的整行发送到 Ouput.txt 文件,所以而不是在实例之上添加整行本身?提前致谢

4

1 回答 1

1

我看不到您的代码正常工作;即使你没有说它应该如何工作(为什么$check取自 args[1] 而不是 args[0]?)。

您的Select-String线路正在获取匹配的线路,然后进行一些选择以丢弃您想要的线路数据,但似乎没有必要。

我将其改写为:

$check = $args[0]
$totalMatches = 0

foreach ( $file in $args[1..$args.Length] )
{
    if ( Test-Path $file ) {
        $matches = Select-String $check $file -AllMatches -SimpleMatch

        Write-Output "There were $($matches.Count) Matches in $file" | Tee-Object -FilePath "output.txt" -Append

        foreach ($match in $matches) {
            Write-Output $match.Line | Tee-Object -FilePath "output.txt" -Append
        }

        Write-Host
        $totalMatches = $totalMatches + $matches.Count
    }
    else {
        Write-Output "File $file does not exist" | Tee-Object -FilePath "output.txt" -Append
    }
}

echo "Total Matches Found: $totalMatches"

变化:

  • 将 $check 作为第一个参数
  • 直接迭代参数而不是计算它们
  • 添加了 -SimpleMatch 所以它不适用于正则表达式,因为你没有提到它们
  • 删除了select-object -expand位,只需获取选择字符串结果
  • 循环遍历结果并从$match.line
  • 添加Tee-Object了在一行中同时写入屏幕和文件的内容
于 2014-03-20T02:08:20.853 回答