Asad Refai
Asad Refai

Reputation: 275

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 i.e. 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

Upvotes: 1

Views: 886

Answers (3)

StingyJack
StingyJack

Reputation: 19479

There are similar questions here on SO like this one, but the only way to retain the information in the CSV is to write the file to disk as your script is executing.

Doing this should be fast, but in case it is not, your script does not have to write the file every time there is more data. It can queue up data and write to disk after some count of data is in the queue and/or time has elapsed (I usually do both).

Upvotes: 0

mjolinor
mjolinor

Reputation: 68341

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 ensure you get all the log data is to write the log events to disk as they occur.

Upvotes: 2

no escape
no escape

Reputation: 11

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

Upvotes: 1

Related Questions