0

I try to read big data log file, in folder C: \ log \ 1 \ i put 2 txt files, i need open-> read all file .txt and find with filter some text like whis: [text]

# Filename: script.ps1


$Files = Get-ChildItem "C:\log\1\" -Filter "*.txt"
foreach ($File in $Files)
{
    $StringMatch = $null
    $StringMatch = select-string $File -pattern "[Error]"
    if ($StringMatch) {out-file -filepath C:\log\outputlog.txt -inputobject $StringMatch}
}
    # end of script

not work

upward unkaind
  • 113
  • 1
  • 11

4 Answers4

1

Would doing something like a select-string work?

Select-String C:\Scripts\*.txt -pattern "SEARCH STRING HERE" | Format-List

Or if there are multiple files you are wanting to parse maybe use the same select-string but within a loop and output the results.

$Files = Get-ChildItem "C:\log\1\" -Filter "*.txt"
foreach ($File in $Files)
{
    $StringMatch = $null
    $StringMatch = select-string $File -pattern "SEARCH STRING HERE"
    if ($StringMatch) {out-file -filepath c:\outputlog.txt -inputobject $StringMatch}
}
k-weaver
  • 38
  • 3
0

This will print out the file name along with the line number in the file. I hope this is what you are looking for.

Remove-Item -Path C:\log\outlog.txt
$Files = Get-ChildItem "C:\log\1\" -Filter "*.txt"
foreach ($File in $Files)
{
    $lineNumber = 0
    $content = Get-Content -Path "C:\log\1\$File"
    foreach($line in $content)
    {
        if($line.Contains('[Error]'))
        {
            Add-Content -Path C:\log\outlog.txt -Value "$File -> $lineNumber"
        }
        $lineNumber++
    }
}
jdwal
  • 189
  • 6
0

Code below works

It selects strings in txt files in your folder based on -SimpleMatch and then appends it to new.txt file.

Though i do not know how to put two simple matches in one line. Maybe someone does and can post it here

Select-String   -Path C:\log\1\*.txt -SimpleMatch "[Error]" -ca  | select -exp line | out-file C:\log\1\new.txt -Append
Select-String   -Path C:\log\1\*.txt -SimpleMatch "[File]" -ca  | select -exp line | out-file C:\log\1\new.txt -Append

Regards

-----edit-----

If you want to you may not append it anywhere just display - simply dont pipe it to out-file

mgiedyk
  • 1
  • 2
0

use index then check it :

New-Item C:\log\outputlog.txt
$Files = Get-ChildItem "C:\log\1\" -Include "*.txt"
foreach ($File in $Files)
{

    $StringMatch = $null
    $StringMatch = Get-Content $File  
    if($StringMatch.IndexOf("[Error]") -ne -1)
    {
        Add-Content -Path C:\log\outputlog.txt -Value ($StringMatch+"
        -------------------------------------------------------------
        ")
    }
}
    # end of script
saftargholi
  • 896
  • 1
  • 9
  • 25