2012-02-17 74 views
0

我需要登錄過程中的一個文本文件,有兩個問題:1。 如何寫在一個文本文件中的錯誤?現在,當電子郵件沒有發送時,沒有記錄。 2.我需要寫時間,日期和事件在一行現在PowerShell中 - 錯誤寫入txt文件,並在同一行

我有這樣的log.txt的:

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

這是我的代碼:

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." 
} 

謝謝。

回答

1
  1. 利用內置Send-MailMessage cmdlet的使用參數-ErrorAction Stop

  2. 使用解決此一個try-catch(見about_try_catch_finally拿起和處理任何錯誤。

    catch$_將錯誤信息(如將在控制檯上顯示),並具有Exception屬性其是(.NET)Exception(或亞類)的實例(I使用下面$_.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()): $_" 
    }