Subscribing to Session Lock/Unlock Events

by Jan 19, 2023

Whenever a user on a Windows box locks his or her session, an event is emitted. Another event is emitted when you unlock your session again. Both events can trigger PowerShell code so you can run any PowerShell code based on a user locking or unlocking a system.

Here are two functions that illustrate this:

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

    $synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
    
    switch($event.SourceEventArgs.Reason) {
    'SessionLock'    { $synthesizer.Speak("Bye bye $env:username!") }
    'SessionUnlock'  { $synthesizer.Speak("Nice to see you again $env:username!") }
    }
  }
}

function End-Fun {
    $events = Get-EventSubscriber | Where-Object { $_.SourceObject -eq [Microsoft.Win32.SystemEvents] } 
    $jobs = $events | Select-Object -ExpandProperty Action
    $events | Unregister-Event
    $jobs | Remove-Job
}

Run the code above, then run Start-Fun to attach code to the events. Whenever you now lock or unlock your PC, you’ll get an audio comment from PowerShell. Of course, you could do other things as well, for example place devices in energy savings mode.

Run End-Fun to remove the event subscriptions again.


Tweet this Tip! Tweet this Tip!