Subscribe to Lock and Unlock Events

by Jun 18, 2019

Whenever a user locks his machine, and whenever a user unlocks a machine, Windows emits an event. PowerShell can subscribe to these events and do things, for example use the text-to-speech engine to emit greetings.

But there are a number of useful actions as well. Maybe you want to clean up when you lock your machine, close all Windows Explorer windows, start a backup, or do something else. Here is the sample code:

function Start-LogMessage {
  $null = Register-ObjectEvent -InputObject ([Microsoft.Win32.SystemEvents]) -SourceIdentifier SessSwitch -EventName "SessionSwitch" -Action {
    Add-Type -AssemblyName System.Speech

    $synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
    
    switch($event.SourceEventArgs.Reason) {
'SessionLock'    
{ $synthesizer.Speak("Have a good one, $env:username!") }
'SessionUnlock'  
{ $synthesizer.Speak("Heya, nice to see you $env:username again!") }
    }
  }
}

function Stop-LogMessage {
    $events = Get-EventSubscriber -SourceIdentifier SessSwitch
    $jobs = $events | Select-Object -ExpandProperty Action
    $events | Unregister-Event
    $jobs | Remove-Job
}

Twitter This Tip! ReTweet this Tip!