I want to catch a PowerShell script as it finishes so that I can do some final processing before it stops. Register-EngineEvent -SourceIdentifier PowerShell.Exiting seems to be the way to do it but it does not work for anything other than trivial applications.
Simple examples work. For example:
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {write-host "This is trivial"}
will print "This is trivial" when the script finishes. However, any action block that needs data passed to it does not get that data. For example:
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {write-host ">> " $($event.MessageData)} -MessageData "This doesn't work"
will only print the two leading angle brackets and not the string "This doesn't work".
Note that I'm calling the script from a Command Prompt (cmd.exe) and it is there that the Write-Host ultimately prints, after PowerShell has exited.
Furthermore, with the exception of the $Event automatic variables, all the others such as $Sender, $Args, $EventArgs etc. are not populated. Also some of the properties of $Event are not populated. For example, $Event.ComputerName prints nothing, but $Event.TimeGenerated prints the current date and time. My computer has a name.
I have included a tiny example program which demonstrates either that I am doing it wrong or that there is some limitation in what can be done with Register-EngineEvent maybe it is even a bug I suppose.
I have spent quite a lot of time searching web sites but I haven't found any examples where they are passing data to an action block for Register-EngineEvent.
sleep 1
write-host "Starting"
sleep 1
write-host "Finished"
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -MessageData "This doesn't work" -Action {write-host ">> " $($event.MessageData)}
sleep 2
I would expect that little script to print "Starting" followed 1 second later by "Finished" and then, after a further 2 seconds the event handler to print ">> This doesn't work". I do get the first two messages but all I get from the handler is ">>".
I am running on Windows 10 with Powershell V5. I am not running it in ISE. I use the command line powershell -file .\try6.ps1 where try6.ps1 is the script I've included above.
If anyone can suggest what I am doing wrong or alternative ways of doing this that would be great but even if it is just that it is a known bug or that I have misunderstood what PowerShell.exiting or Register-EngineEvent are and they can't be used in the way I am trying that would be very helpful as well.
Write-hostback into the same PS session you're exiting from? I can't see how that is supposed to work. What if you write out your message data to file? If that works better, there's your problem.cmd.exe, which is where theWrite-Hostoutput prints after the PS process exits - I've updated the question to make that clearer.