Passing Arguments to Register-EngineEvent Action ScriptblockjQuery find events handlers registered with an objectHow to pass an argument to a PowerShell script?Using Invoke-Command -ScriptBlock on a function with argumentsHow to use Register-Objectevent to invoke a powershell script?Printing object properties in PowershellLoading custom functions in PowerShellPassing values to PowerShell.Exiting event actionspowershell command Line arguments get lost if directly running from CMDHow to pass a script block as parameter and execute multiple times?.NET Object execution

How can one write good dialogue in a story without sounding wooden?

The monorail explodes before I can get on it

Referring to different instances of the same character in time travel

What was the definition of "set" that resulted in Russell's Paradox

Single word for "refusing to move to next activity unless present one is completed."

Why do people keep referring to Leia as Princess Leia, even after the destruction of Alderaan?

Matchmaker, Matchmaker, make me a match

Using Newton's shell theorem to accelerate a spaceship

Does Lufthansa weigh your carry on luggage?

Are there any sports for which the world's best player is female?

Why are Hobbits so fond of mushrooms?

Find image dimensions without importing the full image?

How to convert a file with several spaces into a tab-delimited file?

Cops: The Hidden OEIS Substring

Keep milk (or milk alternative) for a day without a fridge

How is angular momentum conserved for the orbiting body if the centripetal force disappears?

Print the last, middle and first character of your code

US Civil War story: man hanged from a bridge

Are neural networks prone to catastrophic forgetting?

definition of "percentile"

What does Middle English “cheping” mean?

Constructive proof of existence of free algebras for infinitary equational theories

Is anyone advocating the promotion of homosexuality in UK schools?

Why did Harry Potter get a bedroom?



Passing Arguments to Register-EngineEvent Action Scriptblock


jQuery find events handlers registered with an objectHow to pass an argument to a PowerShell script?Using Invoke-Command -ScriptBlock on a function with argumentsHow to use Register-Objectevent to invoke a powershell script?Printing object properties in PowershellLoading custom functions in PowerShellPassing values to PowerShell.Exiting event actionspowershell command Line arguments get lost if directly running from CMDHow to pass a script block as parameter and execute multiple times?.NET Object execution






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















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.










share|improve this question
























  • So you're trying to Write-host back 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.

    – Trix
    Mar 26 at 4:07











  • @Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

    – mklement0
    Mar 26 at 21:32











  • Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

    – Trix
    Mar 27 at 0:27

















2















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.










share|improve this question
























  • So you're trying to Write-host back 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.

    – Trix
    Mar 26 at 4:07











  • @Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

    – mklement0
    Mar 26 at 21:32











  • Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

    – Trix
    Mar 27 at 0:27













2












2








2








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.










share|improve this question
















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.







powershell events event-handling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 21:31









mklement0

149k25 gold badges272 silver badges304 bronze badges




149k25 gold badges272 silver badges304 bronze badges










asked Mar 26 at 2:33









ColinColin

161 bronze badge




161 bronze badge












  • So you're trying to Write-host back 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.

    – Trix
    Mar 26 at 4:07











  • @Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

    – mklement0
    Mar 26 at 21:32











  • Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

    – Trix
    Mar 27 at 0:27

















  • So you're trying to Write-host back 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.

    – Trix
    Mar 26 at 4:07











  • @Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

    – mklement0
    Mar 26 at 21:32











  • Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

    – Trix
    Mar 27 at 0:27
















So you're trying to Write-host back 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.

– Trix
Mar 26 at 4:07





So you're trying to Write-host back 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.

– Trix
Mar 26 at 4:07













@Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

– mklement0
Mar 26 at 21:32





@Trix: Colin is calling the PS script from cmd.exe, which is where the Write-Host output prints after the PS process exits - I've updated the question to make that clearer.

– mklement0
Mar 26 at 21:32













Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

– Trix
Mar 27 at 0:27





Yet another argument for abolishing CMD wrappers for PS scripts. As time goes on, I really don't get why people still do this.

– Trix
Mar 27 at 0:27












1 Answer
1






active

oldest

votes


















0














Note: While this answer contains hopefully useful background information, it does not solve the OP's problem of wanting to pass custom event data to a PowerShell.Exiting event handler.



What Colin encountered is apparently a known bug: see this GitHub issue.




Generally, just to clarify: the PowerShell.Exiting event only fires on exiting a PowerShell session, not a script run inside a session.



Using it in the running session itself (as opposed to using it in a remote session that forwards the event to the caller) limits you to:



  • taking behind-the-scenes action when the session ends

  • using Write-Host to write output that the calling process potentially sees (use of implicit output or Write-Output is no longer an option, because PowerShell's output streams are no longer available at the time the event fires).

You're running a script locally via PowerShell's CLI, powershell.exe which means that the limitations above apply to you.



The automatic event-related variables documented in about_Automatic_Variables do not seem to contain much information when the event fires, as the following command demonstrates:



PS> powershell -c '$null = 
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
$Event, $EventSubscriber, $Sender, $EventArgs, $Args '
ComputerName :
RunspaceId : 1a763430-5cd8-4b74-aaaf-7a90e514518d
EventIdentifier : 1
Sender :
SourceEventArgs :
SourceArgs :
SourceIdentifier : PowerShell.Exiting
TimeGenerated : 3/26/19 12:15:48 AM
MessageData :

SubscriptionId : 1
SourceObject :
EventName :
SourceIdentifier : PowerShell.Exiting
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False



  • $Event exists, and provides the runspace ID and a time stamp reflecting the time of the event.




    • $Event.ComputerName is presumably only populated if the event was forwarded (via Register-EngineEvent's -Forward switch) from a different computer in the context of remoting; if the property is empty, the implication is that the event fired on the local machine.


  • $EventSubscriber exists, but doesn't contain any useable information.


  • $EventArgs, $Sender and $Args are not populated.


Given the above, you could streamline your output to only contain the time stamp of the event and the local computer name's name:



PS> powershell -c '
$null =
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
[pscustomobject] @ TimeGenerated = $Event.TimeGenerated; ComputerName = $env:COMPUTERNAME
# ... call your script
.try6.ps1
'


TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10





share|improve this answer




















  • 1





    Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

    – Colin
    Mar 28 at 3:51











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349039%2fpassing-arguments-to-register-engineevent-action-scriptblock%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Note: While this answer contains hopefully useful background information, it does not solve the OP's problem of wanting to pass custom event data to a PowerShell.Exiting event handler.



What Colin encountered is apparently a known bug: see this GitHub issue.




Generally, just to clarify: the PowerShell.Exiting event only fires on exiting a PowerShell session, not a script run inside a session.



Using it in the running session itself (as opposed to using it in a remote session that forwards the event to the caller) limits you to:



  • taking behind-the-scenes action when the session ends

  • using Write-Host to write output that the calling process potentially sees (use of implicit output or Write-Output is no longer an option, because PowerShell's output streams are no longer available at the time the event fires).

You're running a script locally via PowerShell's CLI, powershell.exe which means that the limitations above apply to you.



The automatic event-related variables documented in about_Automatic_Variables do not seem to contain much information when the event fires, as the following command demonstrates:



PS> powershell -c '$null = 
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
$Event, $EventSubscriber, $Sender, $EventArgs, $Args '
ComputerName :
RunspaceId : 1a763430-5cd8-4b74-aaaf-7a90e514518d
EventIdentifier : 1
Sender :
SourceEventArgs :
SourceArgs :
SourceIdentifier : PowerShell.Exiting
TimeGenerated : 3/26/19 12:15:48 AM
MessageData :

SubscriptionId : 1
SourceObject :
EventName :
SourceIdentifier : PowerShell.Exiting
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False



  • $Event exists, and provides the runspace ID and a time stamp reflecting the time of the event.




    • $Event.ComputerName is presumably only populated if the event was forwarded (via Register-EngineEvent's -Forward switch) from a different computer in the context of remoting; if the property is empty, the implication is that the event fired on the local machine.


  • $EventSubscriber exists, but doesn't contain any useable information.


  • $EventArgs, $Sender and $Args are not populated.


Given the above, you could streamline your output to only contain the time stamp of the event and the local computer name's name:



PS> powershell -c '
$null =
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
[pscustomobject] @ TimeGenerated = $Event.TimeGenerated; ComputerName = $env:COMPUTERNAME
# ... call your script
.try6.ps1
'


TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10





share|improve this answer




















  • 1





    Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

    – Colin
    Mar 28 at 3:51
















0














Note: While this answer contains hopefully useful background information, it does not solve the OP's problem of wanting to pass custom event data to a PowerShell.Exiting event handler.



What Colin encountered is apparently a known bug: see this GitHub issue.




Generally, just to clarify: the PowerShell.Exiting event only fires on exiting a PowerShell session, not a script run inside a session.



Using it in the running session itself (as opposed to using it in a remote session that forwards the event to the caller) limits you to:



  • taking behind-the-scenes action when the session ends

  • using Write-Host to write output that the calling process potentially sees (use of implicit output or Write-Output is no longer an option, because PowerShell's output streams are no longer available at the time the event fires).

You're running a script locally via PowerShell's CLI, powershell.exe which means that the limitations above apply to you.



The automatic event-related variables documented in about_Automatic_Variables do not seem to contain much information when the event fires, as the following command demonstrates:



PS> powershell -c '$null = 
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
$Event, $EventSubscriber, $Sender, $EventArgs, $Args '
ComputerName :
RunspaceId : 1a763430-5cd8-4b74-aaaf-7a90e514518d
EventIdentifier : 1
Sender :
SourceEventArgs :
SourceArgs :
SourceIdentifier : PowerShell.Exiting
TimeGenerated : 3/26/19 12:15:48 AM
MessageData :

SubscriptionId : 1
SourceObject :
EventName :
SourceIdentifier : PowerShell.Exiting
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False



  • $Event exists, and provides the runspace ID and a time stamp reflecting the time of the event.




    • $Event.ComputerName is presumably only populated if the event was forwarded (via Register-EngineEvent's -Forward switch) from a different computer in the context of remoting; if the property is empty, the implication is that the event fired on the local machine.


  • $EventSubscriber exists, but doesn't contain any useable information.


  • $EventArgs, $Sender and $Args are not populated.


Given the above, you could streamline your output to only contain the time stamp of the event and the local computer name's name:



PS> powershell -c '
$null =
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
[pscustomobject] @ TimeGenerated = $Event.TimeGenerated; ComputerName = $env:COMPUTERNAME
# ... call your script
.try6.ps1
'


TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10





share|improve this answer




















  • 1





    Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

    – Colin
    Mar 28 at 3:51














0












0








0







Note: While this answer contains hopefully useful background information, it does not solve the OP's problem of wanting to pass custom event data to a PowerShell.Exiting event handler.



What Colin encountered is apparently a known bug: see this GitHub issue.




Generally, just to clarify: the PowerShell.Exiting event only fires on exiting a PowerShell session, not a script run inside a session.



Using it in the running session itself (as opposed to using it in a remote session that forwards the event to the caller) limits you to:



  • taking behind-the-scenes action when the session ends

  • using Write-Host to write output that the calling process potentially sees (use of implicit output or Write-Output is no longer an option, because PowerShell's output streams are no longer available at the time the event fires).

You're running a script locally via PowerShell's CLI, powershell.exe which means that the limitations above apply to you.



The automatic event-related variables documented in about_Automatic_Variables do not seem to contain much information when the event fires, as the following command demonstrates:



PS> powershell -c '$null = 
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
$Event, $EventSubscriber, $Sender, $EventArgs, $Args '
ComputerName :
RunspaceId : 1a763430-5cd8-4b74-aaaf-7a90e514518d
EventIdentifier : 1
Sender :
SourceEventArgs :
SourceArgs :
SourceIdentifier : PowerShell.Exiting
TimeGenerated : 3/26/19 12:15:48 AM
MessageData :

SubscriptionId : 1
SourceObject :
EventName :
SourceIdentifier : PowerShell.Exiting
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False



  • $Event exists, and provides the runspace ID and a time stamp reflecting the time of the event.




    • $Event.ComputerName is presumably only populated if the event was forwarded (via Register-EngineEvent's -Forward switch) from a different computer in the context of remoting; if the property is empty, the implication is that the event fired on the local machine.


  • $EventSubscriber exists, but doesn't contain any useable information.


  • $EventArgs, $Sender and $Args are not populated.


Given the above, you could streamline your output to only contain the time stamp of the event and the local computer name's name:



PS> powershell -c '
$null =
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
[pscustomobject] @ TimeGenerated = $Event.TimeGenerated; ComputerName = $env:COMPUTERNAME
# ... call your script
.try6.ps1
'


TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10





share|improve this answer















Note: While this answer contains hopefully useful background information, it does not solve the OP's problem of wanting to pass custom event data to a PowerShell.Exiting event handler.



What Colin encountered is apparently a known bug: see this GitHub issue.




Generally, just to clarify: the PowerShell.Exiting event only fires on exiting a PowerShell session, not a script run inside a session.



Using it in the running session itself (as opposed to using it in a remote session that forwards the event to the caller) limits you to:



  • taking behind-the-scenes action when the session ends

  • using Write-Host to write output that the calling process potentially sees (use of implicit output or Write-Output is no longer an option, because PowerShell's output streams are no longer available at the time the event fires).

You're running a script locally via PowerShell's CLI, powershell.exe which means that the limitations above apply to you.



The automatic event-related variables documented in about_Automatic_Variables do not seem to contain much information when the event fires, as the following command demonstrates:



PS> powershell -c '$null = 
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
$Event, $EventSubscriber, $Sender, $EventArgs, $Args '
ComputerName :
RunspaceId : 1a763430-5cd8-4b74-aaaf-7a90e514518d
EventIdentifier : 1
Sender :
SourceEventArgs :
SourceArgs :
SourceIdentifier : PowerShell.Exiting
TimeGenerated : 3/26/19 12:15:48 AM
MessageData :

SubscriptionId : 1
SourceObject :
EventName :
SourceIdentifier : PowerShell.Exiting
Action : System.Management.Automation.PSEventJob
HandlerDelegate :
SupportEvent : False
ForwardEvent : False



  • $Event exists, and provides the runspace ID and a time stamp reflecting the time of the event.




    • $Event.ComputerName is presumably only populated if the event was forwarded (via Register-EngineEvent's -Forward switch) from a different computer in the context of remoting; if the property is empty, the implication is that the event fired on the local machine.


  • $EventSubscriber exists, but doesn't contain any useable information.


  • $EventArgs, $Sender and $Args are not populated.


Given the above, you could streamline your output to only contain the time stamp of the event and the local computer name's name:



PS> powershell -c '
$null =
Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action
[pscustomobject] @ TimeGenerated = $Event.TimeGenerated; ComputerName = $env:COMPUTERNAME
# ... call your script
.try6.ps1
'


TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 21:28

























answered Mar 26 at 4:20









mklement0mklement0

149k25 gold badges272 silver badges304 bronze badges




149k25 gold badges272 silver badges304 bronze badges







  • 1





    Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

    – Colin
    Mar 28 at 3:51













  • 1





    Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

    – Colin
    Mar 28 at 3:51








1




1





Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

– Colin
Mar 28 at 3:51






Thanks for your help and advice and especially for the link to the bug. I did wonder if it was by design since the programmer might argue that there is little point in populating the automatic variable as the session is ending but I see from the bug report that it isn't just for PowerShell.Exiting that this problem exists. Anyway, I have done what I actually wanted to do a different way and that is working fine so all is well. Thanks also to @Trix for the suggestions. Strangely it does work. I did wonder if that was the problem too but it seems not.

– Colin
Mar 28 at 3:51









Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349039%2fpassing-arguments-to-register-engineevent-action-scriptblock%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript