проанализировать файл журнала с помощью powershell и отправить уведомление по электронной почте - PullRequest
0 голосов
/ 07 декабря 2018

Спасибо, что нашли время и помогли мне,

Я пытаюсь создать сценарий powershell для чтения из файла журнала.Если слово «Купить» или «продать» найдено, отправьте мне уведомление по электронной почте, скрипт должен читать только последнюю строку и только один раз, в противном случае несколько уведомлений

расположение файла журнала «C: \ Program Files \ LMFX»Терминал MetaTrader 4 \ MQL4 \ Logs \ 20181206.log "

> tail -5 (last 5 entry of the log file) 0  19:44:20.644    indicator1
> EURUSD,Daily: initialized 0   19:44:20.644    indicator2 EURUSD,Daily:
> initialized 0 19:44:20.645    indicator3 EURUSD,Daily: initialized
> 0 19:44:20.646    indicator4 EURUSD,Daily: initialized
> 0 19:44:20.659    indicator5 EURUSD,Daily: Alert:  ! BUY !  -  EURUSD
> 0 19:44:20.659    indicator5 EURUSD,Daily: Alert:  ! SELL !  -  EURUSD

`

#Powershell Script
$logDir = "C:\Program Files\LMFX MetaTrader 4 Terminal\MQL4\Logs"

function Send-ToEmail([string]$email){
$user = "Sender@email.com"
$pass = ConvertTo-SecureString -String "PASSWORD" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $pass
$body = ":("
$mailParam = @{
    To = "Sender@email.com"
    From = "ALERT ALERT <Reciever@email.com>"
    Subject = "ALERT ALERT ALERT ALERT"
    Body = $body
    SmtpServer = "smtp.gmail.com"
    Port = 587
    Credential = $cred
    #Attachments = "none"     
}

# Send the email with all parameters
Send-MailMessage @mailParam -UseSsl

}

# create a variable to store the previous log line in
$previousLogLine = ''
while ($true) {
$latestLog = Get-ChildItem -Path $logDir -Filter '*.log' | Sort-Object 
LastWriteTime -Descending | Select-Object -First 1
Write-Host "Reading from $($latestLog.Name)"

$logLine = Get-Content -Path $latestLog.FullName -Tail 1
# if this line is different from the previously stored line
# and it contains either "sell" or "buy", then send the email
if ($logLine -ne $previousLogLine -and $logLine -match 'sell|buy') { 
    Send-ToEmail -email "Reciever@email.com"
    # remember this line to compare with the line we get in the next 
    iteration
    $previousLogLine = $logLine
    }
    Start-Sleep -Seconds 1
    cls
   }
`

Ответы [ 2 ]

0 голосов
/ 07 декабря 2018

Я думаю, вам нужно:

  1. проверить последний файл журнала внутри цикла
  2. запомнить последнюю строку, содержащую "buy" или "sell" вчтобы не отправлять одну и ту же строку как письмо снова и снова

Возможно, что-то вроде этого:

$logDir = "C:\Program Files (x86)\Tickmill MT4 Client Terminal\MQL4\Logs\"

function Send-ToEmail([string]$email){
    $user = "sender@email.com"
    $pass = ConvertTo-SecureString -String "PASSWORD" -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential $user, $pass
    $body = ":("
    $mailParam = @{
        To = "sender@email.com"
        From = "ALERT ALERT <Reciever@email.com>"
        Subject = "ALERT : #tail last line"
        Body = $body 
        SmtpServer = "smtp.gmail.com"
        Port = 587
        Credential = $cred
        #Attachments = "none"     
    }

    # Send the email with all parameters
    Send-MailMessage @mailParam -UseSsl
 }

# create a variable to store the previous log line in
$previousLogLine = ''
while ($true) {
    $latestLog = Get-ChildItem -Path $logDir -Filter '*.log' | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Host "Reading from $($latestLog.Name)"

    $logLine = Get-Content -Path $latestLog.FullName -Tail 1
    # if this line is different from the previously stored line
    # and it contains either "sell" or "buy", then send the email
    if ($logLine -ne $previousLogLine -and $logLine -match 'sell|buy') { 
        Send-ToEmail -email "receiver@email.com"
        # remember this line to compare with the line we get in the next iteration
        $previousLogLine = $logLine
    }

    Start-Sleep -Seconds 2
}

Как видите, я также изменил LastAccessTime наLastWriteTime для файла, потому что я думаю, что это более уместно.После тестирования не забудьте изменить эту строку To = "sender@email.com" на To = $email.

Надеюсь, это поможет

0 голосов
/ 07 декабря 2018

Измените свою последнюю часть на следующую, я не думаю, что в этом случае подходит переключатель -wit.Используйте массив для хранения всех отправленных элементов.

while ($true) {
$sent = @()
Get-Content -Path "C:\Program Files (x86)\Tickmill MT4 Client Terminal\MQL4\Logs\$latest" -Tail 1 | %{if(($_ -match "sell" -or $_ -match "buy") -and $sent -notcontains $_){Send-ToEmail  -email "receiver@email.com"; $sent += $_}}

start-sleep 2

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...