< Back

Register-ObjectEvent

Tue Jan 29, 2019 10:23 pm

NAME Register-ObjectEvent



SYNOPSIS

Subscribes to the events that are generated by a Microsoft .NET Framework object.





SYNTAX

Register-ObjectEvent [-InputObject] <PSObject> [-EventName] <String> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-Forward]

[-MaxTriggerCount <Int32>] [-MessageData <PSObject>] [-SupportEvent] [<CommonParameters>]





DESCRIPTION

The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET Framework objects on the local computer or on a remote computer.



When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the Get-Event cmdlet.



You can use the parameters of Register-ObjectEvent to specify property values of the events that can help you to identify the event in the queue.

You can also use the Action parameter to specify actions to take when a subscribed event is raised and the Forward parameter to send remote events

to the event queue in the local session.



When you subscribe to an event, an event subscriber is added to your session. To get the event subscribers in the session, use the

Get-EventSubscriber cmdlet. To cancel the subscription, use the Unregister-Event cmdlet, which deletes the event subscriber from the session.





PARAMETERS

-Action <ScriptBlock>

Specifies commands to handle the events. The commands in the Action run when an event is raised, instead of sending the event to the event

queue. Enclose the commands in braces ( { } ) to create a script block.



The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $EventArgs, and $Args automatic variables, which provide

information about the event to the Action script block. For more information, see about_Automatic_Variables.



When you specify an action, Register-ObjectEvent returns an event job object that represents that action. You can use the Job cmdlets to

manage the event job.



Required? false

Position? 101

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-EventName <String>

Specifies the event to which you are subscribing. Enter the event name. This parameter is required.



The value of this parameter is not a name that you select for the event subscription. It is the name of an event that the .NET Framework

object exposes. For example, the ManagementEventWatcher class has events named EventArrived and Stopped. To find the event name of an event,

use the Get-Member cmdlet.



Required? true

Position? 1

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-Forward [<SwitchParameter>]

Indicates that the cmdlet sends events for this subscription to a remote session. Use this parameter when you are registering for events on a

remote computer or in a remote session.



Required? false

Position? named

Default value False

Accept pipeline input? False

Accept wildcard characters? false



-InputObject <PSObject>

Specifies the .NET Framework object that generates the events. Enter a variable that contains the object, or type a command or expression that

gets the object. This parameter is required.



Required? true

Position? 0

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-MaxTriggerCount <Int32>

Specifies the max trigger count.



The value of the Action parameter can include the $Event, $EventSubscriber, $Sender, $EventArgs, and $Args automatic variables, which provide

information about the event to the Action script block. For more information, see about_Automatic_Variables.



When you specify an action, Register-ObjectEvent returns an event job object that represents that action. You can use the Job cmdlets to

manage the event job.



Required? false

Position? named

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-MessageData <PSObject>

Specifies any additional data to be associated with this event subscription. The value of this parameter appears in the MessageData property

of all events associated with this subscription.



Required? false

Position? named

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-SourceIdentifier <String>

Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is

the GUID that Windows PowerShell assigns.



The value of this parameter appears in the value of the SourceIdentifier property of the subcriber object and of all event objects associated

with this subscription.



Required? false

Position? 100

Default value None

Accept pipeline input? False

Accept wildcard characters? false



-SupportEvent [<SwitchParameter>]

Indicates that the cmdlet hides the event subscription. Use this parameter when the current subscription is part of a more complex event

registration mechanism and it should not be discovered independently.



To view or cancel a subscription that was created with the SupportEvent parameter, use the Force parameter of the Get-EventSubscriber and

Unregister-Event cmdlets.



Required? false

Position? named

Default value False

Accept pipeline input? False

Accept wildcard characters? false



<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug,

ErrorAction, ErrorVariable, WarningAction, WarningVariable,

OutBuffer, PipelineVariable, and OutVariable. For more information, see

about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).



INPUTS

None

You cannot pipe objects to Register-ObjectEvent .





OUTPUTS

System.Management.Automation.PSEventJob

This cmdlet does not generate any output.





NOTES





* Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is

discarded and the event subscription is canceled.



*



Example 1: Subscribe to events when a new process starts



PS C:\\>$Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa

'Win32_Process'"

PS C:\\>$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query

PS C:\\>Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived"



This example subscribes to events generated when a new process starts.



The command uses the ManagementEventWatcher object to get EventArrived events. A query object specifies that the events are instance creation

events for the Win32_Process class.

Example 2: Specify an action to respond to an event



PS C:\\>$Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa

'Win32_Process'"

PS C:\\>$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query

PS C:\\>$Action = { New-Event "PowerShell.ProcessCreated" -Sender $Sender -EventArguments $EventArgs.NewEvent.TargetInstance }

PS C:\\>register-objectEvent -InputObject $ProcessWatcher -EventName "EventArrived" -Action $Action

Id Name State HasMoreData Location Command

-- ---- ----- ----------- -------- -------

2 422cfe5a-65e... Running True New-Event "PowerShe...



This example shows how to specify an action to respond to an event. When you specify an action, events that are raised are not added to the event

queue. Instead, the action responds to the event.



In this example, when an instance creation event is raised indicating that a new process is started, a new ProcessCreated event is raised.



The action uses the $Sender and $EventArgs automatic variables which are populated only for event actions.



The Register-ObjectEvent command returns a job object that represents the action, which runs as a background job. You can use the Job cmdlets,

such as Get-Job and Receive-Job, to manage the background job.



For more information, see about_Jobs.

Example 3: Subscribe to object events on remote computers



PS C:\\>$S = New-PSSession -ComputerName "Server01, Server02"

PS C:\\> Invoke-Command -Session $S -FilePath ProcessCreationEvent.ps1

PS C:\\> Invoke-Command -Session $S { get-event }# ProcessCreationEvent.ps1function Enable-ProcessCreationEvent{ $Query = New-Object

System.Management.WqlEventQuery "__InstanceCreationEvent", `

(New-Object TimeSpan 0,0,1), `

"TargetInstance isa 'Win32_Process'" $ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query $Identifier =

"WMI.ProcessCreated" Register-ObjectEvent -Input $ProcessWatcher -EventName "EventArrived" `

-SourceIdentifier $Identifier -MessageData "Test" -Forward}EnableProcessCreationEvent



This example shows how to subscribe to object events on remote computers.



The first command creates PSSessions on two remote computers and saves them in the $S variable.



The second command uses the FilePath parameter of the Invoke-Command cmdlet to run the ProcessCreationEvent.ps1 script in the each of the

PSSessions in $S.



The script includes a Register-ObjectEvent command that subscribes to instance creation events on the Win32_Process object through the

ManagementEventWatcher object and its EventArrived event.

Example 4: Use the dynamic module in the PSEventJob object



PS C:\\>$Timer = New-Object Timers.Timer

PS C:\\>$Timer.Interval = 500

PS C:\\>$Job = Register-ObjectEvent -InputObject $Timer -EventName Elapsed -SourceIdentifier Timer.Random -Action {$Random = Get-Random -Min 0 -Max

100}

PS C:\\>$Job.gettype().fullnameSystem.Management.Automation.PSEventJob

PS C:\\>$Job | Format-List -Property *

State :

RunningModule : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0

StatusMessage :

HasMoreData : True

Location :

Command : $Random= Get-Random -Min 0 -Max 100

JobStateInfo : Running

Finished : System.Threading.ManualResetEvent

InstanceId : 88944290-133d-4b44-8752-f901bd8012e2

Id : 1

Name : Timer.Random

ChildJobs : {}... PS C:\\>$Timer.Enabled = $True

PS C:\\>& $Job.module {$Random}60

PS C:\\>& $Job.module {$Random}47



This example shows how to use the dynamic module in the PSEventJob object that is created when you include an Action in an event registration.



The first command uses the New-Object cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds).



The third command uses the Register-ObjectEvent cmdlet to register the Elapsed event of the timer object. The command includes an action that

handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the Get-Random cmdlet

generates a random number between 0 and 100 and saves it in the $Randomvariable.



When you use an Action parameter in a Register-ObjectEvent command, the command returns a PSEventJob object that represents the action. The

command saves the job object in the $Job variable.



The PSEventJob object that the Register-ObjectEvent cmdlet returns is also available in the Action property of the event subscriber. For more

information, see Get-EventSubscriber.



The fourth command shows that the $Job variable contains a PSEventJob object. The fifth command uses the Format-List cmdlet to display all of the

properties of the PSEventJob object in a list.



The PSEventJob has a Module property that contains a dynamic script module that implements the action.



The sixth command enables the timer.



The remaining commands use the call operator (&) to invoke the command in the module and display the value of the $Random variable. You can use

the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number

that is being generated when the Elapsed event occurs.



For more information about modules, see about_Modules.



RELATED LINKS

Online Version: http://go.microsoft.com/fwlink/?LinkId=821845

Get-Event

New-EventLog

Register-EngineEvent

Remove-EventLog

Unregister-Event

Wait-Event