我希望能够在远程FTP服务器上的所有文件夹中查找文本字符串。找到后,我需要知道包含文本文件的文件夹的名称但不文件的名称。
如何更改“匹配时操作”以使此脚本(WinSCP Extension Search recursively for text in remote directory / Grep files over SFTP/FTP protocol)以静默方式运行(不在终端中显示任何内容),一旦发现匹配,只需停止并且只显示文件夹的名称(包含带有文本字符串的文件)?还可以用红色显示结果吗?这是脚本中的“匹配操作”部分(我试图包含整个内容,但由于某些原因无法执行此操作)。
我可以在最新的WinSCP自定义搜索文本按钮的帮助下完成此操作(请参阅下面的.ps1脚本,这使得此搜索功能成为可能)。但是,不是仅仅在匹配时停止,搜索一直持续到最后一个文件夹。更糟糕的是,为了找到结果,我需要一直向上滚动并检查每个条目。其中只有一个会列出我的文件夹的名称,因此这是一个很长的过程。
{
# Action on match
# Modify the code below if you want to do another task with
# matching files, instead of grepping their contents
Write-Host ("File {0} matches mask, searching contents..." -f $fileInfo.FullName)
$tempPath = (Join-Path $env:temp $fileInfo.Name)
# Download file to temporary directory
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
$transferResult = $session.GetFiles($sourcePath, $tempPath)
# Did the download succeeded?
if (!$transferResult.IsSuccess)
{
# Print error (but continue with other files)
Write-Host $transferResult.Failures[0].Message
}
else
{
# Search and print lines containing "text".
# Use -Pattern instead of -SimpleMatch for regex search
$matchInfo = Select-String -Path $tempPath -SimpleMatch $text
# Print the results
foreach ($match in $matchInfo)
{
Write-Host ($fileInfo.FullName + ":" + $match.LineNumber + ":" + $match.Line)
}
# Delete temporary local copy
Remove-Item $tempPath
}
}
答案 0 :(得分:0)
{
# Action on match
# Modify the code below if you want to do another task with
# matching files, instead of grepping their contents
$tempPath = (Join-Path $env:temp $fileInfo.Name)
# Download file to temporary directory
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($fileInfo.FullName)
$transferResult = $session.GetFiles($sourcePath, $tempPath)
# Did the download succeeded?
if (!$transferResult.IsSuccess)
{
# Print error (but continue with other files)
Write-Host $transferResult.Failures[0].Message
}
else
{
# Use -Pattern instead of -SimpleMatch for regex search
$matchInfo = Select-String -Path $tempPath -SimpleMatch $text
Remove-Item $tempPath
if ($matchInfo)
{
# Print a path to the file's folder and exit
Write-Host ($fileInfo.FullName -replace "/[^/]*$")
exit
}
}
}