2017-06-02 40 views
2

我正在寫一個腳本運行很長的時間,除其他外,它會累積一組定期保存到文件的日誌條目(不是每次添加條目時)。我需要考慮的問題是,如果腳本在執行中止並且某些日誌文件未保存,會發生什麼情況。在強制退出時執行代碼塊?

有沒有辦法告訴Powershell在實際退出之前運行一個類似Add-Content -Path $LogLocation -Value $NewLogs的代碼塊?

回答

2

Use finally

try { 
    # do stuff 
} finally { 
    Add-Content -Path $LogLocation -Value $NewLogs 
    # this gets executed if an exception is thrown, if the script is stopped, 
    # or if it exits normally; pretty much always 
}