System/Windows Server

[PowerShell] 이벤트뷰어 로그 추출 및 메일 발송

jykim23 2023. 1. 12. 10:33

매주 월요일마다 고객사에게 이벤트뷰어 로그 추출하여 발송하는 업무가 있습니다.

너무 귀찮고 잊어버리는 경우도 있어 powershell로 자동화하였습니다.

 

설치되어 있는 zip을 사용하여 압축했으나 파일 크기가 커서 메일 발송이 안되었습니다.

7z의 압축률을 최대로 하여 진행하였더니 발송되었습니다.

 

$env:LC_ALL='C.UTF-8'

# Get-Date
$getDay = Get-Date

# Last Week
$lastWeek = $getDay.AddDays(-8)
$setDay_after = Get-Date ($lastWeek) -Format "yyyy-MM-dd"
$after = ($setDay_after)+"T15:00:00"

# Monday - for mail
$lastWeek = $getDay.AddDays(-7)
$Monday = Get-Date ($lastWeek) -Format "yyyy-MM-dd"

# Yesterday
$yesterday = $getDay.AddDays(-1)
$setDay_before = Get-Date ($yesterday) -Format "yyyy-MM-dd"
$before = ($setDay_before)+"T15:00:00"

# Today
$today = Get-Date -Format "yyMMdd"


# Mail Credential & Setting
$username = "me@test.com"
$secpasswd = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $secpasswd)

$SMTPServer = "mail.test.com" 
$EmailFrom = "me@test.com"
$EmailTo = "to@test.com"
$WE = "we@test.com"

try
{
    # Create Logs
    wevtutil epl System "/q:*[System[TimeCreated[@SystemTime>='$after' and @SystemTime<='$before']]]" C:\Users\Administrator\Desktop\event_viewer\System_$today.evtx
    wevtutil epl Application "/q:*[System[TimeCreated[@SystemTime>='$after' and @SystemTime<='$before']]]" C:\Users\Administrator\Desktop\event_viewer\Application_$today.evtx
    wevtutil epl Security "/q:*[System[TimeCreated[@SystemTime>='$after' and @SystemTime<='$before']]]" C:\Users\Administrator\Desktop\event_viewer\Security_$today.evtx

    # 7z - 설치 필요
    $7zPath = "C:\Program Files\7-Zip\7z.exe"
    Set-Alias Compress-7Zip $7zPath

    $Source = "C:\Users\Administrator\Desktop\event_viewer\*_$today.evtx"
    $Attachments = "C:\Users\Administrator\Desktop\event_viewer\deepsecurity_$today.7z"

    Compress-7zip a -mx=9 $Attachments $Source


    # Mail
    Send-MailMessage `
    -Encoding ([System.Text.Encoding]::UTF8) `
    -ErrorAction Stop `
    -From $EmailFrom `
    -To $EmailTo `
    -Cc $WE `
    -Attachments $Attachments `
    -Credential $cred `
    -Port 587 `
    -SmtpServer $SMTPServer `
    -Subject "[고객사] $today 이벤트뷰어 보안 로그 전달 건" `
    -Body "안녕하세요. ###입니다.
$Monday ~  $setDay_before 이벤트뷰어 로그 파일 첨부하여 전달 드립니다.
 
감사합니다. 좋은 하루 되세요."
}
catch
{
    # 오류 발생시
    Send-MailMessage `
    -Encoding ([System.Text.Encoding]::UTF8) `
    -From $EmailFrom `
    -To $WE `
    -Credential $cred `
    -Port 587 `
    -SmtpServer $SMTPServer `
    -Subject "[고객사] $today 이벤트뷰어 보안 로그 전달 건 - 실패" `
    -Body "고객사 $today 이벤트뷰어 로그 전달에 실패하였습니다.
받는 사람 : $EmailTo
서버 IP : 1.1.1.1
파일 위치 : $Attachments
PowerShell 로그 : $PSItem
"
}