在文字查找器上打印整行Powershell

时间:2014-03-20 00:36:19

标签: powershell pipeline cmdlet select-string

$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文件,所以相反实例顶部添加整行本身?提前致谢

1 个答案:

答案 0 :(得分: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,它们都写入屏幕并以一行文件