Exibir detalhes do evento na mensagem ao anexar uma tarefa a um evento

2

Quando tento remover hardware com segurança, o Windows 10 me diz que um programa está usando o hardware, mas não me diz qual programa é. Descobri que esta informação é registrada no Visualizador de Eventos em Sistema como Evento 225 como tal:

The application \Device\HarddiskVolume3\Program Files... with process id 4424 stopped the removal or ejection for the device USB....

Esta é uma informação bastante útil que eu gostaria de ver sem ir ao visualizador de eventos todas as vezes. Eu descobri que há um botão no Visualizador de Eventos que informa Anexar tarefa a este evento ... Quando pressionado, ele oferece a opção de exibir uma mensagem toda vez que esse evento é registrado. Eu gostaria que a tarefa exibisse os detalhes do evento toda vez que o evento fosse logado. Parece que poderia ser possível, mas não sou especialista em nível de sistema.

Existe uma maneira fácil de alcançar meu objetivo? Se não estiver na mensagem de exibição, existe uma maneira de fazer o script de um arquivo de lote para executar, em vez de me informar essas informações?

    
por Yaroslav 01.04.2018 / 16:28

2 respostas

1

A ação "exibir uma mensagem" está obsoleta e pode, na verdade, não fazer nada. Em vez disso, você pode usar o PowerShell! Salve isso como um arquivo .ps1 em algum lugar no computador, por exemplo C:\evtmsg.ps1 :

Add-Type -AssemblyName System.Windows.Forms
$lastEvt = Get-WinEvent -LogName 'System' -MaxEvents 20 | ? { $_.Id -eq 225 } | select -First 1
[System.Windows.Forms.MessageBox]::Show(($lastEvt.Message), 'Ejection Failed')

Este script obtém a instância mais recente do evento 225 do log do sistema e usa a biblioteca de formulários do Windows para exibir sua mensagem.

Use o comando Anexar tarefa a este evento do Event Viewer em uma instância do evento 225. Na tela Ação, escolha "iniciar um programa" e especifique powershell para o programa / script ser executado . Na caixa "adicionar argumentos", coloque esta linha, ajustada para onde você salvou o script do PowerShell:

-executionpolicy bypass -windowstyle hidden -file C:\evtmsg.ps1

A alteração deve entrar em vigor imediatamente após a criação da tarefa.

    
por 01.04.2018 / 20:01
0

Enviar notificação por e-mail quando um ID de evento específico é gerado

Eu tenho uma solução semelhante que gostaria de compartilhar apenas no caso de alguém poder usá-la, já que parece me ajudar e gritar comigo quando preciso explicitamente, com base em IDs de evento .

Scheduling

This solution uses a Task Scheduler job that has many different Triggers of the On an event for when it is to execute. You specify the specific Event ID that's to "trigger" an execution.

enter image description here enter image description here


PowerShell Script

Here's a PowerShell script that uses a Gmail account with a password to send an email which will include the detail of the applicable events in its body.

Note: You have to pass the Gmail account password as the first argument to the PowerShell script.

$EmailPassword=$args[0]
$event = get-eventlog -LogName System -EntryType Error -newest 1

$PCName = $env:COMPUTERNAME
$Username = "LocalMailBox"
$EmailBody = $event | format-list -property * | out-string
$EmailFrom = "$PCName <[email protected]>"
$EmailTo = "[email protected]" 
$EmailSubject = "New Event Log [System]"
$SMTPServer = "smtp.gmail.com" 
Write-host "Sending Email"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword); 
$SMTPClient.Send($EmailFrom, $EmailTo, $EmailSubject, $EmailBody)
Start-Sleep -s 10

From the Action tab you will create an Action defined as:

  • Action: Start a program
  • Program/script: Powershell
  • Add arguments (optional): -ExecutionPolicy Bypass -File "C:\Scripts\PSScript.ps1" "GmailPassword"
  • Start in (optional): C:\Windows\System32\WindowsPowerShell\v1.0 enter image description here

From the General tab of the scheduled task, be sure the Run whether user is logged on or not and the Run with highest privileges options are both selected.

enter image description here


The Email

With everything listed above set just as specified, this will ensure that when those specific System Event IDs are generated which you defined "triggers" for that an email will be sent, and hopefully with applicable detail as per the event that triggers each.

I only mention this as I have noticed that if two event that match the PowerShell logic of $event | format-list -property * | out-string are created quickly, that the body of the email will contain the latest event's detail based on timing.

Remember that regardless of the Event ID body content and even if it's not pertinent to the specific events you defined as triggers it is certain that those defined triggered indeed triggered this email so give it some attention when received.

enter image description here

    
por 02.04.2018 / 03:50