在 Windows 上锁定计算机之前运行脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5881887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:47:40  来源:igfitidea点击:

Running a script before locking a computer on Windows

windowspowershell

提问by Peter Rossi

I've written some powershell which allows me to harness the power of the keyboard media keys to control any music that's currently running.

我编写了一些 powershell,它允许我利用键盘媒体键的力量来控制当前正在运行的任何音乐。

What I want to be able to do is run the script on the event of the computer being locked. So I can pause/stop the music. Then once the machine is unlocked, resume the music. Cool huh?!

我想要做的是在计算机被锁定的情况下运行脚本。所以我可以暂停/停止音乐。然后一旦机器解锁,恢复音乐。酷吧?!

My first 2 attempts have been:

我的前 2 次尝试是:

1 - WMI Event registration

1 - WMI 事件注册

This is the on lock event

这是上锁事件

Register-wmievent –query "Select * from __instancecreationevent within 1 where TargetInstance isa 'Win32_NTLogEvent' And TargetInstance.EventCode = 4800" -Action {write-host "Pausing`r`n"; set-playpausetrack}

This is the unlock event

这是解锁事件

Register-wmievent –query "Select * from __instancecreationevent within 1 where TargetInstance isa 'Win32_NTLogEvent' And TargetInstance.EventCode = 4801" -Action {write-host "Resuming`r`n"; set-playpausetrack}

Unfortunately, I think the lock event fires too late, at which point background interaction is halted by the OS for security reasons. When I unlock the computer it fires both the locked and unlocked events.

不幸的是,我认为锁定事件触发得太晚了,此时操作系统出于安全原因停止了后台交互。当我解锁计算机时,它会同时触发锁定和解锁事件。

2 - Using the task scheduler "On workstation locked" trigger

2 - 使用任务调度程序“在工作站锁定”触发器

Similar issue to above, but it also runs in a different context so doesn't work properly.

与上述问题类似,但它也在不同的上下文中运行,因此无法正常工作。

Does anyone know how to get a script to run before the system actually locks? I.e. is there an event I can watch for which triggers before?

有谁知道如何在系统实际锁定之前运行脚本?即是否有一个事件我可以监视哪些触发器?

采纳答案by JPBlanc

This seems to work

这似乎有效

PS> $sysevent = [microsoft.win32.systemevents]
PS> $sysevent

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    SystemEvents                             System.Object


PS> Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {[console]::Beep()}

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
1               fa48b95f-299... NotStarted False                                [console]::Beep()

You can find the list of SytemEvents in Microsoft documentation.

您可以在 Microsoft 文档中找到SytemEvents 列表

DisplaySettingsChanged  Occurs when the user changes the display settings. 
DisplaySettingsChanging Occurs when the display settings are changing. 
EventsThreadShutdown    Occurs before the thread that listens for system events is terminated. 
InstalledFontsChanged   Occurs when the user adds fonts to or removes fonts from the system. 
LowMemory               Occurs when the system is running out of available RAM. 
PaletteChanged          Occurs when the user switches to an application that uses a different palette. 
PowerModeChanged        Occurs when the user suspends or resumes the system. 
SessionEnded            Occurs when the user is logging off or shutting down the system. 
SessionEnding           Occurs when the user is trying to log off or shut down the system. 
SessionSwitch           Occurs when the currently logged-in user has changed. 
TimeChanged             Occurs when the user changes the time on the system clock. 
TimerElapsed            Occurs when a windows timer interval has expired. 
UserPreferenceChanged   Occurs when a user preference has changed. 
UserPreferenceChanging  Occurs when a user preference is changing. 

To unregister event

取消注册事件

PS> Unregister-Event -SubscriptionId 1

If you want to be able to distinguish Lock and Unlock the SessionSwitchEventHandlerreceives two parameters

如果要能够区分 Lock 和 UnlockSessionSwitchEventHandler接收两个参数

  1. The source of the event.
  2. SessionSwitchEventArgs indicating the type of the session change event.
  1. 事件的来源。
  2. SessionSwitchEventArgs 指示会话更改事件的类型。

The SessionSwitchEventArgsown one propertie Reasonwhich is an enum SessionSwitchReasonvalues are :

作为枚举值的SessionSwitchEventArgs自己的一个属性是:ReasonSessionSwitchReason

ConsoleConnect        A session has been connected from the console.  
ConsoleDisconnect     A session has been disconnected from the console.  
RemoteConnect         A session has been connected from a remote connection.  
RemoteDisconnect      A session has been disconnected from a remote connection.  
SessionLogon          A user has logged on to a session.  
SessionLogoff         A user has logged off from a session.  
SessionLock           A session has been locked.  
SessionUnlock         A session has been unlocked.  
SessionRemoteControl  A session has changed its status to or from remote controlled mode.

Example :

例子 :

PS> Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {[console]::Beep();Write-Host ($args[1]).Reason}

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
9               20e6ecd4-fc0... NotStarted False                                [console]::Beep();fore...


PS >
SessionLock

SessionUnlock

If you want a list of events suscribed you can use Get-EventSubscriber:

如果您想要订阅事件列表,您可以使用Get-EventSubscriber

SubscriptionId   : 5
SourceObject     : Microsoft.Win32.SystemEvents
EventName        : SessionSwitch
SourceIdentifier : 96fbabe4-518a-47b5-8a3f-bb89c68f7f39
Action           : System.Management.Automation.PSEventJob
HandlerDelegate  :
SupportEvent     : False
ForwardEvent     : False

回答by ravikanth

Try and create a permanent event consumer for the lock/unlock events. Check http://powerevents.codeplex.comand look at an example of using PowerEvents module at http://www.ravichaganti.com/blog/?p=1951

尝试为锁定/解锁事件创建一个永久的事件使用者。检查http://powerevents.codeplex.com并在http://www.ravichaganti.com/blog/?p=1951查看使用 PowerEvents 模块的示例