【发布时间】:2023-03-15 02:25:01
【问题描述】:
已经有一些这样的问题,但没有一个对我的目的来说足够具体。
我需要在 10,000 个日志文件中搜索特定字符串,然后输出该字符串所在的每一行,同时创建该日志文件的副本。
我几乎可以在 BATCH 文件中使用它。我想我碰壁了,需要开始使用我以前很少使用的 powershell。
:更新
感谢 Trondh,我能够将他的脚本用作完美的基础,并添加我需要的功能。希望这对其他人有帮助:)
#Folder to search
$folder = read-host "Please specify the location of the search "
#Search for:
$SearchTerm = read-host "type in the word you want to find Eg. Error or JobID "
#Files to include in search
$FileFilter = read-host "Enter Date Part of file filter Eg. 20140123 or 201401 "
#File to store log file copies in
$destinationfolder = "Backup-$SearchTerm"
#File to store results in
$newfile = "Search-Log-$SearchTerm.txt"
#Get the files according to filter. Recurse, but exclude directories
$files = Get-ChildItem -Path $folder -Include @("*$filefilter*.*") -recurse | where {$_.PSIsContainer -eq $false}
foreach ($file in $files)
{
$result = $file | Select-String $SearchTerm
$result | add-content $newfile
New-Item -ItemType Directory -Force -Path $destinationfolder
#If we get a hit, copy the file
if ($result)
{
Write-host "Found match in file $($file.Name) ($($file.Directory))"
#Add result to file
$file | Copy-Item -Destination $destinationfolder
#Also output it
$result
}
}
Write-Host "Search Completed!"
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
【问题讨论】:
-
我的建议是使用一种可以输出为本地(或几乎)代码的语言,如 C++、C#、JAVA 等。因为批量解析文件需要很长时间
标签: batch-file powershell xcopy findstr