$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"
基本上,我创建了一个快速的应用程序来查找搜索的单词,并检查文件中的实例,有人知道如何编辑它来发送整个行,这个单词被发现在output .txt文件中,而不是在实例的顶部添加整行本身吗?提前感谢
我看不出你的代码工作正常;即使你没有说它应该如何工作(为什么$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
,它既写屏幕,也写文件在一行