none
Poweshell: How to get event Id and sent an email RRS feed

  • Question

  • I'm trying to write a powershell script that will take the event ID (like 9999) and send an email

    My conditional is not working and i don't know why

    #export a certain eventlog with specified log name and event ID for last 24 hours. 
    $ChkLog = 99999
    Get-WinEvent -LogName "Microsoft-Windows-Hyper-V-VMMS/Admin" -MaxEvents 1000 -EA SilentlyContinue | Where-Object {$_.id -in 99999 -and $_.Timecreated -gt (Get-date).AddHours(-24)}
    If ($ChkLog -eq $True) {
    Write-Host "noo, does not exists"

    Send-MailMessage -From "name@company.com" -To "name@company.com" -SmtpServer "emailserver" -Subject "test_failed" -Body "bad one"
    }
    Else
    {
    Write-Host "Yippee, 99999  exists"

    Send-MailMessage -From "name@company.com" -To "name@company.com" -SmtpServer "emailserver" -Subject "test_suc" -Body "Good one"
    }

    Thank you very much!


    Na vida há dois caminhos mais só um que vai na direção certa

    Wednesday, February 15, 2017 4:57 PM

Answers

  • Here is the correct way to do a log extraction.  It will be much faster:

    $hash = @{
    	LogName = 'Microsoft-Windows-Hyper-V-VMMS/Admin'
    	ID = 99999
    	StartTime = [datetime]::Today.AddHours(-24)
    }
    Get-WinEvent -FilterHashtable $hash -MaxEvents 1000

    To check the results:

    if(Get-WinEvent -FilterHashtable $hash -MaxEvents 1000){
    	Write-Host 'Log records exists'
    }else{
    	Write-Host 'no records found'
    }


    \_(ツ)_/

    • Marked as answer by Julio Melo Thursday, February 16, 2017 3:24 PM
    Wednesday, February 15, 2017 7:46 PM

All replies

  • You set $ChkLog to 9999 and then your if statement tests if it is $true.


    PS C:\> 9999 -eq $true
    False
    


    -- Bill Stewart [Bill_Stewart]

    Wednesday, February 15, 2017 6:50 PM
    Moderator
  • Here is the correct way to do a log extraction.  It will be much faster:

    $hash = @{
    	LogName = 'Microsoft-Windows-Hyper-V-VMMS/Admin'
    	ID = 99999
    	StartTime = [datetime]::Today.AddHours(-24)
    }
    Get-WinEvent -FilterHashtable $hash -MaxEvents 1000

    To check the results:

    if(Get-WinEvent -FilterHashtable $hash -MaxEvents 1000){
    	Write-Host 'Log records exists'
    }else{
    	Write-Host 'no records found'
    }


    \_(ツ)_/

    • Marked as answer by Julio Melo Thursday, February 16, 2017 3:24 PM
    Wednesday, February 15, 2017 7:46 PM
  • Never test an expression against $true or $false for the exact reason Bill gave an example for.  The outcome can be unpredictable and the exercise is pointless.


    \_(ツ)_/

    Wednesday, February 15, 2017 7:49 PM
  • Thank you mate!

    It's working fine!


    Na vida há dois caminhos mais só um que vai na direção certa

    Thursday, February 16, 2017 3:24 PM