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?

4

3 回答 3

2

当您从参数$OnLock中调用它时,请删除周围的大括号。-Action

于 2013-10-22T18:37:02.553 回答
1

事件操作在无法访问局部变量的单独运行空间中运行。尝试使其成为全局范围内的函数。

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

$sysevent = [microsoft.win32.systemevents]

Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {OnLock} -SourceIdentifier "ExecuteOnLock"
于 2013-10-22T16:16:28.890 回答
0

我今天发现了一种有趣的方法,可以通过使用前面提到的 cmdlet 的 MessageData 参数,从通过 Register-ObjectEvent cmdlet 的 Action 参数中传递的脚本块调用脚本的本地函数,而无需将这些函数归属于全局范围。查看下一个代码片段:

&{  
  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
}
于 2017-05-26T20:23:23.330 回答