2012-02-17 4 views
0

이 과정을 텍스트 파일에 기록해야하는데 두 가지 문제가 있습니다 : 1. 텍스트 파일에 오류를 쓰는 방법은 무엇입니까? 이제 전자 메일을 보내지 않으면 아무 것도 기록되지 않습니다. 2. 내가 log.txt에이이powershell - .txt 파일과 한 줄로 오류를 작성하십시오.

이제 한 줄에서 시간, 날짜 및 이벤트를 작성해야하는 것은 :

function write-log{ 
param(
[string]$mytext, 
[string]$fgc 
) 
if(!$fgc){$fgc="Black"} 
write-host $mytext -foregroundcolor $fgc 
$myfile = "c:\gnupg\subor\log.txt" 
Get-Date | Out-File $myfile -append 
$mytext | Out-File $myfile -append 
} 

if(test-path "d:\vm\shared pre ws08R2+SQL05\SFRB\*.chk") { 
echo "Subor .chk existuje a jeho nazov je " 
get-childitem "d:\vm\shared pre ws08R2+SQL05\SFRB\*.chk" -Name 
$a = get-childitem "d:\vm\shared pre ws08R2+SQL05\SFRB\*" -include *.chk -name | Foreach-Object {$a -replace ".chk", ""} 

if(test-path d:\vm\"shared pre ws08R2+SQL05"\SFRB\$a.gpg) { 
    Write-Log $a".gpg existuje." Green 

    Write-Log "Presuvam do banky subor $a.gpg.." Green 

    Move-Item "d:\vm\shared pre ws08R2+SQL05\SFRB\$a.gpg" c:\gnupg\subor\$a.gpg 
    Write-Log "Presun ukonceny." Green 

    Write-Log "Presuvam do banky subor $a.chk.." Green 
    Move-Item "d:\vm\shared pre ws08R2+SQL05\SFRB\$a.chk" c:\gnupg\subor\$a.chk 
    Write-Log "Presun ukonceny. Subor je pripraveny na spracovanie." Green 

    Write-Log "Posielam notifikacne maily.." Green 
    $emailFrom = "[email protected]" 
    $emailTo = "[email protected]" 
    $subject = "subject" 
    $body = "subor presunuty" 
    $smtpServer = "87.244.217.54" 
    $smtp = new-object Net.Mail.SmtpClient($smtpServer) 
    $smtp.Send($emailFrom, $emailTo, $subject, $body) 
    # Write-Log "Maily odoslane." Green 

     } 
     else { 
       Write-Log " Chyba: $a.gpg neexistuje" Magenta 
     } 
} else { 
Write-log "V cielovom adresari neexistuje ziadny subor .chk." 
} 

감사합니다 :

17. feb. 2012 10:47:34 
Chyba: .gpg neexistuje 
17. feb. 2012 10:57:28 
Test.gpg existuje. 

이 내 코드입니다 . 매개 변수 -ErrorAction Stop와 붙박이 Send-MailMessage cmdlet에의

답변

1
  1. 만들기 사용. 이 주위에 시도 - 캐치 (참조

  2. 사용 about_try_catch_finally 픽업 오류를 처리 할 수 ​​있습니다.

    catch 블록에서) 콘솔에 표시하는 것처럼 $_이 (오류 메시지가 될 것이며,하기 Exception 제 (.NET) 인 특성 Exception (또는 서브 클래스) 예 (나는 그것이 어떤 진단의 중요한 부분이기 때문에 특히이 유형을보고 아래 $_.Exception.GetType() 사용)이 있습니다.

예를에 내가 가지고있는 스크립트 :

try { 
     $trans = (MakeSummaryMessage) + "`r`n`r`n" + $trans 
     Send-MailMessage -From $emailFrom ` 
         -To $emailTo ` 
         -SmtpServer $emailServer ` 
         -Subject $subject" ` 
         -Body $trans ` 
         -Encoding ([System.Text.Encoding]::UTF8) ` 
         -ErrorAction Stop 
     $emailSent = $true 
    } catch { 

     Write-EventLog -LogName $eventLog -Source $eventSource -EntryType "Error" ` 
      -EventId 100 -Message "Failed to send email: $($_.Exception.GetType()): $_" 
    } 
관련 문제