【问题标题】:Powershell event handler contextPowershell 事件处理程序上下文
【发布时间】:2017-09-09 14:24:41
【问题描述】:

我尝试使用下一条命令订阅 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

【问题讨论】:

  • 我可以确认,这在我的 Server 2012 R2 机器上的 PowerShell 控制台中不起作用。在 ISE 中没有问题。

标签: powershell events event-handling


【解决方案1】:

似乎与以下问题相同:Question about ISE vs Console with SystemEvents

解决方案是将控制台作为 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

【讨论】:

    猜你喜欢
    • 2011-04-24
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多