Passing Arguments to Register-EngineEvent Action Scriptblock - powershell

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.

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 GitHub issue #7000.
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 | Out-string | Write-Host
}'
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 }| Format-List | Out-String | Write-Host
}
# ... call your script
.\try6.ps1
'
TimeGenerated : 3/26/2019 8:57:53 AM
ComputerName : Workstation10

Related

VSCode & Powershell: How to stop script and unregister object?

I have a snippet that works fine. It registers an objectevent as follows (snippet):
Register-ObjectEvent $Watcher -EventName Created -SourceIdentifier FileCreated -Action {
It works fine, but I can't seem to get the script to fully stop and unregister. When I use "normal" methods to stop code (listed below), when I rerun the code (via F5) I get error:
Register-ObjectEvent : Cannot subscribe to the specified event. A subscriber with the source identifier 'FileCreated' already exists.
The only way I can unregister it (so far) is to terminate the powershell.exe process, which also kills the powershell run time within VSCode (throwing errors, forcing a manual restart).
I start the code by hitting F5
To stop the code, I have tried:
Shift-F5
Ctrl-C (in the powershell terminal area)
Nothing works except as described above.
What am I missing?
For debugging purposes only, where you often force-stop your script, there are 2 options. Either run the unregister-Event line manually so the event is unregistered or do add something like that near the top f your script. (at least before the Register-ObjectEvent )
Unregister-Event -SourceIdentifier FileCreated -EA 0
-EA 0 is the same as -ErrorAction SilentlyContinue and will prevent the script from throwing an error when you are on a new session and the event was never registered yet.
Note: This should not be in your production script and is only meant as a debugging help. (If you want to keep it on hand, I'd say comment it out at least on the prod. version of the script)
Your production version of the script should implement Unregister-Event properly though, something more akin to:
$FileWatcherReg = #{
InputObject = $Watcher
EventName = 'Created'
SourceIdentifier = 'FileCreated'
MessageData = #{WatchQueue = $WatchQueue; Timer = $WatchTimer }
Action = {
if ($null -ne $event) {
Write-Host "Path: $($Event.SourceArgs.FullPath) - ($($Event.Timegenerated))"
}
}
}
Register-ObjectEvent #FileWatcherReg
while ($true) {
Start-Sleep -Milliseconds 100
# Logic to exit the loop at some point.
}
# Exit script logic ...
Unregister-Event -SourceIdentifier FileCreated
Similar to Sage's example above, is this larger example. It structures the event clearly, and shows how by keeping the script running, you can then cancel the script, which will trigger the cleanup block.
So there is something to be said for this approach. (However, I continue to see the whole Register-ObjectEvent as kind of a TSR... your code stays resident... forever... waiting for the relevant event....)
The example:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/using-filesystemwatcher-correctly-part-2#

Monitoring Start-Process with Timer

I am running in debug mode in ISE. I am starting a separate powershell script from another secondary script using start-process and specifying it's -file parameter from the primary script. I have a timer in the primary script where I am trying to execute some other code.
Please consider the following:
$timer = new-object timers.timer
$timerID = [guid]::NewGuid()
$timer.Interval = 10000
$complete = 0
$action = {
write-host "Complete Ticker: $complete"
if($complete -eq 1)
{
write-host "Completed"
$timer.stop()
Unregister-Event $timerID
}
}
Register-ObjectEvent -InputObject $timer -EventName elapsed –SourceIdentifier $timerID -Action $action
$timer.start()
$shellScript = "-file C:\Test.ps1"
$powershellArguments = $shellScript
Start-Process "powershell.exe" -Wait -ArgumentList $powershellArguments
$complete = 1
The other script is called successfully, and displays, however the timer does not appear to tick unless the script window started with the start-process is closed. The expected result is in that the interval specified that a breakpoint could be set in the action and hit while the secondary script is running.
Is there something perhaps wrong with the above code?
The start-process that starts PS uses the -Wait parameter. That prevents $action from running.
I'm not sure what the code is trying to accomplish via the timer and $action. What it would do, though (if not for -Wait), is write "Complete Ticker: 0" every ten seconds until the invoked PS completes when it will write "Complete Ticker: 1".
If the invoked PS runs longer than 10 seconds * height_of_the_parent_PS_console_in_lines, you won't really be able to see much in the way of output - the screen will be full of "Complete Ticker: 0" messages and you'd have to watch closely to see the screen kind of flicker every 10 seconds. Even if the invoked PS runs more quickly than that, the output doesn't tell how long the invoked PS will run or even that it's making progress.
In essence it's kind of like having the user watch der blinkenlights - interesting to look at possibly, but not too informative.
But if that's what the timer code is supposed to do it can be replaced by a simple loop after the start-process that checks if the invoked PS has completed and if not outputs the "Complete Ticker: 0" message.
Use the -passthru argument to start-process and then check the status of via the returned process object in the loop.

Web service call, if application is running

I'm looking for a way to execute a web form submittal if an application is running. I'm not sure the best approach, but I did create a PowerShell script that accomplishes what I want.
while($true) {
(Invoke-WebRequest -Method post 'Http://website.com').Content;
Start-Sleep -Seconds 600;
}
Now what I'd like to do is run this only when an application is running and then quit if the application is no longer running. I suspect maybe a Windows service would be the answer? If so, any idea how I could accomplish this?
I had also thought about running this as a Google Chrome extension, but then my googlefu was exhausted. For Chrome, I would just need the script and no need to check on the .exe.
Any thoughts or help would be appreciated. Again, I'm way out of my depth here but have found a need to create something so dummy steps would be much desired.
If you know the name of the process that runs for the application, you can do the following:
$processname = "thing"
# Wait until the process is detected
Do {
Sleep 60
} Until (Get-Process $processName)
# Once it is detected, run the script
# < SCRIPT RUN CODE HERE >
While (1) {
# Monitor the process to make sure it is still running
If (Get-Process $processName) {
Continue
}
Else {
# Stop the script, because the process isn't running.
# < SCRIPT STOP CODE HERE >
# Wait until the process is detected again
Do {
Sleep 60
} Until (Get-Process $processName)
# Once it is detected again, run the script
# < SCRIPT RUN CODE HERE >
}
# You can add in a delay here to slow down the loop
# Sleep 60
}
I think what you're looking for might be WMI eventing. You can register for (and respond to) events that occur within WMI, such as:
When a process starts or stops
When a service starts or stops
When a process exceeds a certain amount of memory usage
When a new version device driver is installed
When a computer is assigned to a new organizational unit
When a user logs on or off
When an environment variables changes
When a laptop battery drops below a certain threshold
Thousands of other cases
To register for WMI events, use the Register-WmiEvent cmdlet. You can use the -Action parameter to declare what PowerShell statements to execute when a matching event is detected. Here is a simple example:
# 1. Start notepad.exe
notepad;
# 2. Register for events when Notepad disappears
# 2a. Declare the WMI event query
$WmiEventQuery = "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'Win32_Process' and TargetInstance.Name = 'notepad.exe'";
# 2b. Declare the PowerShell ScriptBlock that will execute when event is matched
$Action = { Write-Host -ForegroundColor Green -Object ('Process stopped! {0}' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name) };
# 2c. Register for WMI events
Register-WmiEvent -Namespace root\cimv2 -Query $WmiEventQuery -Action $Action -SourceIdentifier NotepadStopped;
# 3. Stop notepad.exe
# Note: For some reason, if you terminate the process as part of the same thread, the event
# doesn't seem to fire correctly. So, wrap the Stop-Process command in Start-Job.
Start-Job -ScriptBlock { Stop-Process -Name notepad; };
# 4. Wait for event consumer (action) to fire and clean up the event registration
Start-Sleep -Seconds 6;
Unregister-Event -SourceIdentifier NotepadStopped;
FYI: I developed a PowerShell module called PowerEvents, which is hosted on CodePlex. The module includes the ability to register permanent WMI event subscriptions, and includes a 30+ page PDF document that helps you to understand WMI eventing. You can find this open-source project at: http://powerevents.codeplex.com.
If I were to adapt your code to something that is more practical for you, it might look something like the example below. You could invoke the code on a periodic basis using the Windows Task Scheduler.
# 1. If process is not running, then exit immediately
if (-not (Get-Process -Name notepad)) { throw 'Process is not running!'; return; }
# 2. Register for events when Notepad disappears
# 2a. Declare the WMI event query
$WmiEventQuery = "select * from __InstanceDeletionEvent within 5 where TargetInstance ISA 'Win32_Process' and TargetInstance.Name = 'notepad.exe'";
# 2b. Declare the PowerShell ScriptBlock that will execute when event is matched
# In this case, it simply appends the value of the $event automatic variable to a
# new, global variable named NotepadEvent.
$Action = { $global:NotepadEvent += $event; };
# 2c. Register for WMI events
Register-WmiEvent -Namespace root\cimv2 -Query $WmiEventQuery -Action $Action -SourceIdentifier NotepadStopped;
# 3. Wait indefinitely, or until $global:NotepadEvent variable is NOT $null
while ($true -and -not $global:NotepadEvent) {
Start-Sleep -Seconds 600;
(Invoke-WebRequest -Method post 'Http://website.com').Content;
}

DotNetZip ExtractProgress events in PowerShell

I'm extracting a ZIP file in PowerShell by using the DotNetZip library, and I want to display progress. I'm using the following code:
try {
$zip = [Ionic.Zip.ZipFile]::Read($ZipFileName)
Register-ObjectEvent `
-InputObject $zip `
-EventName ExtractProgress `
-SourceIdentifier ExtractProgress `
-Action {
[Console]::Beep()
Write-Host $Sender
Write-Host $SourceEventArgs
} | Out-Null
$zip.ExtractAll($Destination, 'OverwriteSilently')
}
finally {
Unregister-Event -SourceIdentifier ExtractProgress
$zip.Dispose()
}
My problem is that I don't see the events (no beep, no Write-Host) until the very end. I'm expecting to see progress events during the process.
Initially, I thought it was because Register-ObjectEvent queued the events, but the PowerShell help says that -Action is invoked immediately, without the event being queued.
If I write the equivalent code in a C# console application, then I see the progress events as each file is extracted, as expected, which means that (as far as I can tell) DotNetZip is doing the right thing. Note that the events are raised on the same thread that called ExtractAll.
What am I doing wrong?
(Windows 7 x64, PowerShell 2.0, configured to use .NET 4.0)

Automatically pulling data from a PowerShell job while running

While trying to do something quite possibly beyond the means of PowerShell I seem to have ran into a brick wall. I have a main form script, which orchestrates most of my functions but I need another script to open a listener (system.Net.Sockets.Udpclient.Receive) and keep feeding in information to a textbox in the main form throughout the entire program's running.
For the life of me I can't get around this daft non-child environment that jobs suffer from; no dot sourcing, no global scoped variables, nothing. I can put an object-listener on it for statechanged to completion and then open another listener and try and bodge this way but it will get very messy and unreliable.
As a workaround I would love a TCP/UDP listener which doesn't hang the application for a response, an event to pull on hasmoredata or a way of updatign the textbox in the main script from within the job.
You can return data from a job by raising an event and forwarding it back to the local session.
Here is an example:
$job = Start-Job -Name "ReturnMessage" -ScriptBlock {
# forward events named "MyNewMessage" back to job owner
# this even works across machines
Register-EngineEvent -SourceIdentifier MyNewMessage -Forward
while($true) {
sleep 2
$i++
$message = "This is message $i."
# raise a new progress event, assigning to $null to prevent
# it ending up in the job's output stream
$null = New-Event -SourceIdentifier MyNewMessage -MessageData $message
}
}
$event = Register-EngineEvent -SourceIdentifier MyNewMessage -Action {
Write-Host $event.MessageData -ForegroundColor Green
}
<# Run this to stop job and event listner
$job,$event| Stop-Job -PassThru| Remove-Job
#>
Note that you can still type at the prompt while the job is running. Execute the code in the block comments to stop the job and event listner.