Description
Sometimes powerJobs shows the warning "The application cannot be restarted! There are open documents!".
Cause
This happens because some custom jobs open documents, but do not close them before exiting the job. This can either happen if the job is terminated without errors, using return or exit. More often though this happens when the job terminates with an error die to an external API call throwing an error, syntax errors, etc.
Solution
The proper way to do this would be to avoid the issue in the first place. Call Close-Document as soon as possible after Open-Document. In most scripts the document is not needed anymore after calling Export-Document so that is a good place to close it. When you call external APIs or functions from the .NET framework make sure to implement proper error handling.
This is usually a lot of work so the safest way to resolve this issue is to close all open documents before you open a new document.
In every script and module, before you call Open-Document run the following code to make sure all documents are closed properly
foreach ($pjpApplication in $Host.Applications.GetEnumerator()) {
while ($pjpApplication.Value.OpenDocuments.Count -ge 1) {
$null = Close-Document -Document $Host.Applications[$pjpApplication.Key].OpenDocuments[0]
}
}