0

I am trying to execute a script when the user locks the computer. This is how my script looks like:

$OnLock = 
{
    Write-Host  -ForeGround Green "System Locked"
}


$sysevent = [microsoft.win32.systemevents]

Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {$OnLock} -SourceIdentifier "ExecuteOnLock"

The problem is that it does not print anything on the console window but if i write the code in the Action switch, it works fine.

Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -SourceIdentifier "ExecuteOnLock" -Action {Write-Host  -ForeGround Green "System Locked"} 

Is there something i am missing while calling $OnLock script block?

2
  • 1
    Remove the braces around $OnLock when you are calling it from the -Action parameter. Commented Oct 22, 2013 at 16:17
  • Can you post it as Answer so that i can accept it? Commented Oct 22, 2013 at 16:31

3 Answers 3

2

Remove the braces around $OnLock when you are calling it from the -Action parameter.

Sign up to request clarification or add additional context in comments.

Comments

1

Event actions run in a separate runspace that can't access local variables. Try making it a function in the Global scope.

Function Global:OnLock { 
Write-Host  -ForeGround Green "System Locked" }

$sysevent = [microsoft.win32.systemevents]

Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {OnLock} -SourceIdentifier "ExecuteOnLock"

Comments

0

I've discovered today a funny way to call local functions of a script from a scriptblock passed in the Action parameter of the Register-ObjectEvent cmdlet by using the MessageData parameter the previously mentioned cmdlet without attributing these functions to global scope. Look at the next code snippet:

&{  
  function sesbeg{
    'Lots of usfull actions in the "sesbeg" function'
  }
  function rqincs{
    'Lots of usfull actions in the "rqincs" function'
  }
  function sesfin{
    'Lots of usfull actions in the "sesfin" function'
  }
  function outincs{
    'Lots of usfull actions in the "outincs" function'
  }
  function shincs{
    sesbeg
    $my.incs=rqincs
    sesfin
    if($my.incs){$my.incs;outincs;$refr=$my.refr*1000}
    else{write-host 'The data was not received';$refr=1000}
    $my.tim.Interval=$refr
  }
  function tmbeg{
    $my.tim=New-Object System.Timers.Timer ($my.refr*1000)
    $my.tim.AutoReset=$True
    $my.subs=Register-ObjectEvent $my.tim Elapsed `
               -Action {$Event.MessageData|%{$my=$_.my;&$_.fn}|Out-Host} `
               -MessageData @{my=$my;fn=$function:shincs}
    $my.tim.Start()
  }
  $my=@{refr=5}
  tmbeg
  shincs
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.