我是一名网络工程师,我编写了一个小而有效的PS脚本来搜索日志(或与此相关的任何文件)中的文本模式。现在,此脚本仅输出行,文件名等。现在,我想扩展脚本,以便在找到一行时告诉我该行,文件名等,以及该行的内容。
所以它应该像这样:
LineNumber Filename Path Pattern
---------- -------- ---- -------
4 190719_Success.log C:\skripte\190719_Success.log test
.log第4行上的文本应显示在此处
5 190719_Success.log C:\skripte\190719_Success.log test
.log第5行上的文本应显示在此处
很抱歉,希望您能理解我的意思。
由于我是PS脚本的新手,我有点迷失了应该如何实现这一目标,或者甚至是可能的。
这是我的代码提供者:
Clear-Host
$Pfad = Read-Host "Bitte Pfad angeben" #Enter Directory Path to Search
$Suchbegriff = Read-Host "Suchbegriff eingeben" #Enter Pattern to search for
New-Item -ItemType directory -Path C:\Skripte -erroraction 'silentlycontinue' #create C:\Skripte Folder
Remove-Item -Path C:\Skripte\Suchergebnis.txt -erroraction 'silentlycontinue' #Cleanup from previous run
Remove-Item -Path C:\Skripte\Indizierung.csv -erroraction 'silentlycontinue' #Cleanup
cd $Pfad
echo $file.fullname
echo ""
select-string -Path .\*.* -Pattern "$Suchbegriff" -erroraction 'silentlycontinue' | Select-Object LineNumber,Filename,Path,Pattern | ft -wrap #Search the specified Directory
echo ""
while(($Create = Read-Host -Prompt "Unterordner durchsuchen? J für Ja, N für Nein") -ne "x") #Userinput if Subdirectorys should be searched aswell
{
switch ($Create)
{
'J'
{
Get-Childitem -erroraction 'silentlycontinue' | Get-ChildItem -Recurse -erroraction 'silentlycontinue' | Where-Object {$_.PSIsContainer} | Export-CSV -NoClobber -NoTypeInformation -Path C:\Skripte\Indizierung.csv #Get all Subdirectorys and put them in a CSV, two GCI are needed to reliably get all subdirectories.
$Files = import-csv -Delimiter ',' -Path C:\Skripte\Indizierung.csv #Import CSV
foreach ($File in $Files)
{
cd $file.fullname
echo $file.fullname
echo ""
select-string -Path .\*.* -Pattern "$Suchbegriff" -erroraction 'silentlycontinue' | Select-Object LineNumber,Filename,Path,Pattern | ft -wrap
echo ""
pause
exit
}
}
'n'
{
pause
Exit
}
}
}
答案 0 :(得分:0)
看看下面的代码。我添加了一个处理文件的循环以及对输入的一些验证以及您向控制台显示行内容的请求。
代码已修改(@Theo:感谢您的输入)
m = dfName['Name'].str.contains('_')
#is sample data .reset_index(drop=True) not necessary, added for general solution
df1 = dfName[~m].reset_index(drop=True)
print(df1)
Name
0 Hello
1 Spider
2 Captain
3 Superman
df2 = dfName[m].reset_index(drop=True)
print(df2)
Name
0 Hello_1
1 Superman_1