2017-06-02 78 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 
}