本文介绍了关于ISE与带有SystemEvents的控制台的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在PowerShell ISE中运行以下命令时,它可以完美运行,这给了我与"AccountLock"或"AccountUnlock"完全相同的原因.但是,当我在提升的Powershell控制台中运行此确切命令时,它根本不会在控制台中返回sessionswitch原因.解锁后不返回任何内容.

When I run the following in PowerShell ISE, it works perfectly, gives me the reason "AccountLock" or "AccountUnlock" exactly as it's supposed to. However, when I run this exact command in an elevated powershell console, it does not return the sessionswitch reason at all in console. It returns nothing after an unlock.

我检查了 Get-EventSubscriber 以及 Get-Job ,两者看起来都已成功创建.订阅者和用户的屏幕截图职位:

I checked Get-EventSubscriber as well as Get-Job and both look successfully created.Screenshot of Subscriber & Job:

Register-ObjectEvent -InputObject $([microsoft.win32.systemevents]) -EventName "SessionSwitch" -Action {write-host $event.SourceEventArgs.Reason}

我想做的一件事是让Windows检测会话何时解锁(在用户将其密码与域同步后)并打开程序.

One thing I would like to do is have windows detect when the session is unlocked (after a user syncs their password with the domain) and open a program.

操作系统:Windows 10版本:5.1 Build 17134 R 590

OS: Windows 10Version: 5.1 Build 17134 R 590

推荐答案

环顾四周后,我找不到使用[windows.win32.systemevents]的好方法,所以我联系了Lee Holmes.他说这是因为Powershell控制台主机默认在单线程单元(STA)模型中运行.如果您在MTA中运行它,则可以正常运行.

After a lot of looking around, i couldn't find a good way to use [windows.win32.systemevents], so i reached out to Lee Holmes. He said it is because the powershell console host runs by default in the Single Thread Apartment (STA) model. If you run it in MTA, it works fine.

最简单的解决方法是在脚本的开头使用与此类似的代码,以确保您处于MTA模式,如果不启动新的Powershell进程,则重新启动该脚本.

Simplest workaround is to use code similar to this at the beginning of your script to ensure you are in MTA mode, and if start a new powershell process if you are not and reload the script.

if ([System.Threading.Thread]::CurrentThread.ApartmentState -ne [System.Threading.ApartmentState]::MTA)
{
    powershell.exe -MTA -File $MyInvocation.MyCommand.Path
    return
}

这篇关于关于ISE与带有SystemEvents的控制台的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:45