简体   繁体   中英

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

I am having a PowerShell script. 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.

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.

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.

So I am in search of a PowerShell command or snippet which tells us that the code execution is stopped. 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.

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.

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.

The Catch block only runs if there is an error. The Finally block always runs, even if you abort the script with Ctrl+C.

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.

If they hit Ctrl+C while it's exporting, you may still lose some log data.

The best way to insure you get all the log data is to write the log events to disk as they occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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