Share via


Register-ObjectEvent

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

Syntax

Register-ObjectEvent
        [-InputObject] <PSObject>
        [-EventName] <String>
        [[-SourceIdentifier] <String>]
        [[-Action] <ScriptBlock>]
        [-MessageData <PSObject>]
        [-SupportEvent]
        [-Forward]
        [-MaxTriggerCount <Int32>]
        [<CommonParameters>]

Description

The Register-ObjectEvent cmdlet subscribes to events that are generated by .NET 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.

Examples

Example 1: Subscribe to events when a new process starts

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.

$queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1),
    "TargetInstance isa 'Win32_Process'"
$Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters
$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query
Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived"

Example 2: 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.

$queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1),
    "TargetInstance isa 'Win32_Process'"
$Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters
$ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query
$newEventArgs = @{
    SourceIdentifier = 'PowerShell.ProcessCreated'
    Sender = $Sender
    EventArguments = $EventArgs.NewEvent.TargetInstance
}
$Action = { New-Event @newEventArgs }
Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived" -Action $Action

Id   Name               PSJobTypeName   State       HasMoreData   Location   Command
--   ----               -------------   -----       -----------   --------   -------
 5   3db2d67a-efff-...                 NotStarted   False                    New-Event @newEventArgs

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

This example shows how to subscribe to object events on remote computers. This example uses the Enable-ProcessCreationEvent function that is defined in the ProcessCreationEvent.ps1 script file. This script is available to all computers in the example.

# ProcessCreationEvent.ps1
function  Enable-ProcessCreationEvent {
    $queryParameters = "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1),
        "TargetInstance isa 'Win32_Process'"
    $Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters

    $objectEventArgs = @{
        Input = New-Object System.Management.ManagementEventWatcher $Query
        EventName = 'EventArrived'
        SourceIdentifier = 'WMI.ProcessCreated'
        MessageData = 'Test'
        Forward = $True
    }
    Register-ObjectEvent @objectEventArgs
}

$S = New-PSSession -ComputerName "Server01, Server02"
Invoke-Command -Session $S -FilePath ProcessCreationEvent.ps1
Invoke-Command -Session $S { Enable-ProcessCreationEvent }

The first we create PSSessions on two remote computers and save them in the $S variable. Next, the Invoke-Command cmdlet run the ProcessCreationEvent.ps1 script in the each of the PSSessions in $S. This action creates the Enable-ProcessCreationEvent function in the remote sessions. Finally, we run the Enable-ProcessCreationEvent function in the remote sessions.

The function 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

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. First we createand and enable a timer object, then set the interval of the timer to 500 (milliseconds). The Register-ObjectEvent cmdlet registers the Elapsed event of the timer object. The PSEventJob object is saved in the $Job variable and is also available in the Action property of the event subscriber. For more information, see Get-EventSubscriber.

Whenever the timer interval elapses, an event is raised and the action is executed. In this case, the Get-Random cmdlet generates a random number between 0 and 100 and saves it in the $Random variable.

$Timer = New-Object Timers.Timer
$Timer.Interval = 500
$Timer.Enabled = $True
$objectEventArgs = @{
    InputObject = $Timer
    EventName = 'Elapsed'
    SourceIdentifier = 'Timer.Random'
    Action = {$Random = Get-Random -Min 0 -Max 100}
}
$Job = Register-ObjectEvent @objectEventArgs
$Job | Format-List -Property *
& $Job.module {$Random}
& $Job.module {$Random}

State         : Running
Module        : __DynamicModule_53113769-31f2-42dc-830b-8749325e28d6
StatusMessage :
HasMoreData   : True
Location      :
Command       : $Random = Get-Random -Min 0 -Max 100
JobStateInfo  : Running
Finished      : System.Threading.ManualResetEvent
InstanceId    : 47b5ec9f-bfe3-4605-860a-4674e5d44ca8
Id            : 7
Name          : Timer.Random
ChildJobs     : {}
PSBeginTime   : 6/27/2019 10:19:06 AM
PSEndTime     :
PSJobTypeName :
Output        : {}
Error         : {}
Progress      : {}
Verbose       : {}
Debug         : {}
Warning       : {}
Information   : {}
60
47

The PSEventJob has a Module property that contains a dynamic script module that implements the action. Using the call operator (&), we invoke the command in the module to display the value of the $Random variable.

For more information about modules, see about_Modules.

Parameters

-Action

Specifies the commands to handle the event. 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. These variables 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.

Type:ScriptBlock
Position:101
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-EventName

Specifies the event to which you are subscribing.

The value of this parameter must be the name of the event that the .NET 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.

Type:String
Position:1
Default value:None
Required:True
Accept pipeline input:False
Accept wildcard characters:False

-Forward

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.

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-InputObject

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

Type:PSObject
Position:0
Default value:None
Required:True
Accept pipeline input:False
Accept wildcard characters:False

-MaxTriggerCount

Specifies the maximum number of times an event can be triggered.

Type:Int32
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-MessageData

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.

Type:PSObject
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-SourceIdentifier

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 PowerShell assigns.

The value of this parameter appears in the value of the SourceIdentifier property of the subscriber object and all event objects associated with this subscription.

Type:String
Position:100
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

-SupportEvent

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 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.

Type:SwitchParameter
Position:Named
Default value:None
Required:False
Accept pipeline input:False
Accept wildcard characters:False

Inputs

None

You cannot pipe objects to Register-ObjectEvent.

Outputs

None or System.Management.Automation.PSEventJob

When you use the Action parameter, Register-ObjectEvent returns a System.Management.Automation.PSEventJob object. Otherwise, it 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.