PoshCode Archive  Artifact [e7f14f34a7]

Artifact e7f14f34a7871b55f589edd65841efa0694422d4b7ba9182572a13ca22d70893:

  • File HenryCeliafa-nokiamail-c.ps1 — part of check-in [94767fd093] at 2018-06-10 13:43:37 on branch trunk — From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes (user: Lee Holmes size: 1412)

# encoding: ascii
# api: powershell
# title: HenryCeliafa@nokiamail.c
# description: From Windows PowerShell Cookbook (O’Reilly) by Lee Holmes
# version: 0.1
# type: script
# author: Lee Holmes
# license: CC0
# x-poshcode-id: 4602
# x-archived: 2016-06-05T08:37:10
# x-published: 2016-11-12T07:59: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