PoshCode Archive  Artifact [d31b7f2545]

Artifact d31b7f2545769e1a66d0ef6e008916d4a4466e2ba324de21664eb2955b282735:

  • File Register-TemporaryEvent.ps1 — part of check-in [9956e37e2b] at 2018-06-10 13:07:04 on branch trunk — From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes (user: Lee Holmes size: 1412)

# encoding: ascii
# api: powershell
# title: Register-TemporaryEvent.
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# type: script
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 2205
# x-archived: 2016-06-03T06:40:30
# x-published: 2011-09-09T21:42:00
#
#
##############################################################################
##
## Register-TemporaryEvent
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Registers an event action for an object, and automatically unregisters
itself afterward.

.EXAMPLE

PS >$timer = New-Object Timers.Timer
PS >Register-TemporaryEvent $timer Disposed { [Console]::Beep(100,100) }
PS >$timer.Dispose()
PS >Get-EventSubscriber
PS >Get-Job

#>

param(
    ## The object that generates the event
    $Object,

    ## The event to subscribe to
    $Event,

    ## The action to invoke when the event arrives
    [ScriptBlock] $Action
)

Set-StrictMode -Version Latest

$actionText = $action.ToString()
$actionText += @'

$eventSubscriber | Unregister-Event
$eventSubscriber.Action | Remove-Job
'@

$eventAction = [ScriptBlock]::Create($actionText)
$null = Register-ObjectEvent $object $event -Action $eventAction