Executing PowerShell on Computer Lock

by Apr 24, 2012

PowerShell can respond to system events such as locking or unlocking a session. Here is a fun sample. Provided you have your sound card turned on, your computer will say good-bye when you press WIN+L and welcome you back when you log on again:

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("See you later $env:username!") }
    'SessionUnlock'  { $synthesizer.Speak("Hey, welcome back $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
}

Twitter This Tip! ReTweet this Tip!