Reputation: 69
I have got a problem.
1.The first situation
Process has already started.
And I want to do something after the current process is completed.
For example
$process=[System.Diagnostics.Process]::GetProcessesByName("notepad")
And
Register-ObjectEvent $process Exited -Action {}
But in this case, it's not working
How Can I Register Event "Exited"?
2. The Second situation
The Process has not yet been started.
How I can to wait for start process?)
Upvotes: 1
Views: 1100
Reputation: 18747
First part is answered by Mathias R. Jessen with [System.Diagnostics.Process]::GetProcessesByName("notepad") | foreach {Register-ObjectEvent $_ Exited -Action { ... } }
For second part, the solution is below. Credit goes here PDQ.com - Register-ObjectEvent
You need to use WQL queries to monitor for process start event, then set up a query watcher that will fire an event in response of some process getting started, then listen with Register-ObjectEvent
on that watcher. Code-copy-paste:
$Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'"
$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query
$Action = { New-Event "PowerShell.ProcessCreated" -Sender $Sender -EventArguments $EventArgs.NewEvent.TargetInstance }
register-objectEvent -InputObject $ProcessWatcher -EventName "EventArrived" -Action $Action
Upvotes: 1