Powershell 事件处理程序上下文



我尝试使用下一个命令订阅SessionSwitch事件:

Register-ObjectEvent -InputObject ([Microsoft.Win32.SystemEvents])
-EventName 'SessionSwitch' -Action { Write-Host "Session Changed" }

它适用于Windows 7,Windows Server 2008 R2和Windows Server 2012 R2上的Powershell ISE。我锁定并解锁会话,并在shell中出现"会话已更改"消息。但是如果我在Windows Server 2012 R2上的"通用"Powershell shell中运行命令,则它不起作用。看来我错过了一些重要的东西。请告诉我我错过了什么。

"常见" - Powershell.exe, Powershell ISE - powershell_ise.exe

似乎与以下问题相同:关于ISE与带有系统事件的控制台的问题

解决方法是将控制台作为 MTA 而不是 STA 运行:

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

有关更多详细信息,请参阅答案:https://stackoverflow.com/a/60641410/1819480

相关内容

最新更新