2013-10-26 3 views
1

전 PowerShell의 새로운 기능입니다. 사전에 사과드립니다. 나는 여기에서 발견 된 스크립트로 시작했다 : Getting Event Log contents by email (엄청난 신용과 감사). 기본적으로이 오류 코드가 발생하면 매 60 초마다 게시되므로 가장 자주 발생하는 20 개의 이벤트가 기본 테이블의 HTML로 변환 될 때마다 이메일 만 필요합니다. 모든 것이 ISE에서 스크립트를 실행할 때 훌륭하게 작동하지만 일반 PowerShell 콘솔이나 예약 된 작업으로 실행될 때 전자 메일이 보내지지 않습니다. 한 가지주의 할 점은 PowerShell 콘솔의 모든 전자 메일 섹션을 실행하고 HTML 파일 EventID-To-HTML | Out-File -FilePath $filePath -Append에 쓸 수 있습니다. 새로운 것, 나는 정확하게 올바르게 취급하지 않을 것이라 확신합니다, 그래서 피드백은 항상 감사합니다. 고마워요PowerShell 스크립트가 ISE 외부에서 실행되지 않습니다

Clear-Host 

# ======================== 
# Collection Data Section 
# ======================== 

function EventID-To-HTML($ComputerName = $env:COMPUTERNAME) { 
    $FROMTIME = (Get-Date).AddMinutes(-60) 
    $Event = get-eventlog -log Application -newest 20 | where {$_.EventID -eq 7071 -AND $_.TimeGenerated -gt $FROMTIME} 
    $eventstring = @() 
    Foreach ($i in $Event) { 
     $eventstring += $i.Message + ", " +$i.TimeGenerated 
    } 

    if ($eventstring -eq $NULL){exit} 

    $GetEventDate = get-eventlog -log Application -newest 1 | where {$_.EventID -eq 7071 -AND $_.TimeGenerated -gt $FROMTIME} 
    $EventDate = $GetEventDate.TimeGenerated 

    $htmlStart = "<HTML> 
        <HEAD> 
         <style> 
         body {background-color:rgb(238, 238, 238);} 
         body, table, td, th {font-family:Calibri; color:Black; Font-Size:11pt} 
             th {font-weight:bold; background-color:rgb(78, 227, 48);} 
             td {background-color:rgb(255, 190, 0);} 
         </style> 
        </HEAD> 
        <BODY><div align=center> 
        <h2><b><br><br>Security Alert: <span Style='font-style:normal; color:Blue'>**Camera(s) Down**</span></b></h2> 
        <p><b><br>This event occurred at: <span Style='font-style:italic; color:Blue'>$EventDate on $ComputerName</span></b></p>" 

    $htmlEnd = '' 
    $htmlStart 

    $eventstring | ForEach-Object {Add-Member -InputObject $_ -Type NoteProperty -Name Camera -Value $_; $_} | ConvertTo-Html -Property Camera 
    #$eventstring | %{ New-Object PsObject -Prop @{Length = $_.Length; String = $_} } | ConvertTo-HTML 

    $htmlStart = '' 
    $htmlStart = $htmlStart + "<br><br><br><i><span Style='color:red'>This report has been generated by software</i> <br><i>Please DO NOT reply.</i></div>" 
    $htmlStart 
    $htmlEnd = '' 
    $htmlEnd 
} 

# ====================== 
# Email Section 
# ====================== 

# Make sure $eventstring has something in it first as to not send an empty message 
if ($eventstring.count -ge 1) { 
    $strFrom = "[email protected]" 
    $strTo = "[email protected]" 
    $strSubject = "Subject" 
    $strSMTPServer = "SMPT Server name" 

    $objEmailMessage = New-Object system.net.mail.mailmessage 
    $objEmailMessage.From = ($strFrom) 
    $objEmailMessage.To.Add($strTo) 
    $objEmailMessage.Subject = $strSubject 
    $objEmailMessage.IsBodyHTML = $true 
    $objEmailMessage.Body = EventID-To-HTML 

    $objSMTP = New-Object Net.Mail.SmtpClient($strSMTPServer) 
    $objSMTP.Send($objEmailMessage) 
} 

답변

1

나는이 문제가 $ eventstring의 범위 지정 문제라고 생각합니다. 그것은 EventID-To-HTML 함수 내에서 생성됩니다. 범위 지정이 ISE에서 작동하는 방식 때문에이 변수는 함수가 실행 된 후에도 계속 사용할 수 있습니다. 일반적으로 함수는 자체 범위에서 실행되며 범위가 존재하면 범위가 삭제되고 해당 범위에서 만들어진 모든 변수가 사용됩니다.

함수를 도트 소싱하여 테스트하여 현재 범위에서 실행되도록 할 수 있습니다.

. EventID-To-HTML | Out-File -FilePath $filePath -Append 

점과 함수 이름 사이의 공백에 유의하십시오. 그곳에 있어야합니다.

피할 수있는 한 가지 방법은 레이 대신 배열 목록과 같은 컬렉션 형식을 사용하는 것입니다.

$eventstring = new-object collections.arraylist 
    Foreach ($i in $Event) { 
     $eventstring.add("$($i.Message), $($i.TimeGenerated)") > $nul 
+0

감사합니다. 좀 더 설명이 필요합니다. 내 생각에 전역 변수에서 $ eventstring을 만들면 해결할 것입니다. 맞습니까? – user2921987

+1

할 수는 있지만 전역 변수를 사용하는 것은 일반적으로 나쁜 습관으로 간주됩니다. 범위 지정 문제를 해결하는 다른 방법이 있습니다. 하나는 arralist 배열의 istead를 사용하는 것입니다. 예를 들어 대답을 업데이트했습니다. – mjolinor

+0

+1 전역 변수를 옹호합니다. – Neolisk

관련 문제