简体   繁体   English

PowerShell命令或代码以了解脚本执行是否已停止

[英]PowerShell command or code to know if script execution has been stopped

I am having a PowerShell script. 我有一个PowerShell脚本。 It contains the logic of migrating files from file system to some cloud share. 它包含将文件从文件系统迁移到某些云共享的逻辑。 At the end of the script execution ie end of migration, I am exporting the log to csv file which contains data like whether file migrated with or with out error. 在脚本执行结束(即迁移结束)时,我将日志导出到csv文件,该文件包含数据(例如文件是否有错误迁移)。

Now there can be situations where migration engineer stops the script manually using ctrl+Break or Shift+F5 or the script gets terminated due to some critical error. 现在可能存在迁移工程师使用ctrl+BreakShift+F5手动停止脚本的情况,或者由于某些严重错误而终止了脚本的情况。

Since my PowerShell code is generating a csv file at the end of successful execution, this interruption which is in between will not create any log file. 由于我的PowerShell代码在成功执行结束时生成了一个csv文件,因此介于两者之间的此中断将不会创建任何日志文件。

So I am in search of a PowerShell command or snippet which tells us that the code execution is stopped. 因此,我正在寻找一个PowerShell命令或代码段,该命令或代码段告诉我们代码执行已停止。 And then we export the log file 然后我们导出日志文件

Not sure what your real question is. 不知道你真正的问题是什么。 Maybe you could post the code here. 也许您可以在此处发布代码。 You can add 你可以加

$ErrorActionPreference = 'Stop'

at the start of your script, that will stop the script when an error is encountered. 在脚本的开头,遇到错误时将停止脚本。

Try using Try/Catch statement for proper error handling. 尝试使用Try / Catch语句进行正确的错误处理。

http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx

Use Try/Catch/Finally. 使用尝试/捕获/最后。

Put whatever code is going to notify you the script exited in the Finally block. 放置将要通知您的代码,以通知您在Final模块中退出的脚本。

Try this: 尝试这个:

Try { while  (1) {$i++} }
Catch{ Write-Host 'Catch block ran' }
Finally{Write-host 'Finally block ran'}

Notice if you abort the script with Ctrl+C the Catch block does not run, but the Finally block does. 请注意,如果使用Ctrl + C中止脚本,则Catch块不会运行,而Final块会运行。

The Catch block only runs if there is an error. Catch块仅在出现错误时运行。 The Finally block always runs, even if you abort the script with Ctrl+C. 即使使用Ctrl + C中止脚本,Final块也始终运行。

So: 所以:

Try {#your script here}
Catch {}
Finally {#Export log file}

And the log file will be exported if the script is aborted during the Try block. 如果在Try块中脚本被中止,则将导出日志文件。

If they hit Ctrl+C while it's exporting, you may still lose some log data. 如果在导出时按Ctrl + C,您可能仍然会丢失一些日志数据。

The best way to insure you get all the log data is to write the log events to disk as they occur. 确保获取所有日志数据的最佳方法是在发生日志事件时将其写入磁盘。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM