读取文件夹中的txt文件,并按每个样本打印一些文本

时间:2016-10-25 17:34:44

标签: powershell

我尝试读取大数据日志文件,在文件夹C:\ log \ 1 \ i中放入2个txt文件,我需要打开 - >读取所有文件.txt并使用过滤器查找一些文字,如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

无法正常工作

4 个答案:

答案 0 :(得分:0)

会做像select-string这样的工作吗?

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

或者,如果您想要解析多个文件,可以使用相同的select-string但在循环中输出结果。

$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}
}

答案 1 :(得分:0)

这将打印出文件名以及文件中的行号。我希望这就是你要找的东西。

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++
    }
}

答案 2 :(得分:0)

以下代码

它根据-SimpleMatch选择文件夹中txt文件中的字符串,然后将其附加到new.txt文件。

虽然我不知道如何将两个简单的匹配放在一行中。也许有人会这样做并且可以在这里发布

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

此致

- - - - - - - - 编辑

如果你想要,你可能不会在显示的任何地方附加它 - 只是不要将它管道输出到文件外

答案 3 :(得分:0)

使用index然后检查它:

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
相关问题