簡體   English   中英

Powershell-Register-ObjectEvent MSTSC問題-未在正確的時間觸發事件

[英]Powershell - Register-ObjectEvent mstsc issue - Event not fired at the right time

我目前正在編寫一個Powershell(5.0)腳本來運行和管理Windows瘦客戶機上RDP會話的結束。

RDP會話結束后,腳本將運行特定功能。 為此,將mstsc作為進程運行(使用Start-Process cmdlet)。然后使用Register-ObjectEvent來注冊和捕獲mstsc進程的Exited事件。

如果在沒有-ArgumentList參數的情況下運行mstsc(如下例所示),則一切正常。 RDP會話結束時或登錄前關閉RDP登錄對話框時,將觸發Exited事件。

$rdpSession = Start-Process -FilePath mstsc -PassThru
$RegisteredEvent = Register-ObjectEvent -InputObject $rdpSession -EventName Exited -Action {rdpSessionEnd} -Verbose 

使用-ArgumentList參數提供自定義rdp文件路徑(如下面的示例所示)使Exited事件在mstsc進程開始后立即觸發,而不是等待rdp會話結束。

$rdpSession = Start-Process -FilePath mstsc -ArgumentList C:\RDS\RDS.rdp -PassThru 
$RegisteredEvent = Register-ObjectEvent -InputObject $rdpSession -EventName Exited -Action {rdpSessionEnd}

該腳本將在64位Windows上運行。 之前,我曾閱讀過有關運行32位或64位版本的OS的system32或SysWOW64文件夾mstsc版本的信息。 使用mstsc.exe的兩個實例及其完整路徑都不能解決問題。

任何幫助將不勝感激 !

PetSerAl,您讓我重回正軌,因為它是正確的,我應該再進一步探索!

實際上,第一個mstsc進程啟動一個子mstsc進程,然后退出。

通過這種方式可以完成工作(例如,請參見下面的縮短和未優化的代碼):

  1. 使用rdp文件參數運行“父” mstsc進程。

  2. 注冊“父”進程的“退出”事件,以便在引發該語句時,注冊“子” mstsc進程的“退出”事件以運行特定功能(假設在創建子進程之前已創建“子”進程)。父進程退出自身,而子進程是唯一剩余的名為“ mstsc”的運行進程)。

  3. 結束或中止rdp會話會使子mstsc進程“退出”並運行已注冊的功能。

     function registerRdpSessionExitedEvent { # Registering the "exited" event of the child process (the rdp session itself) to run the <rdpSessionEnd> function when raised $rdpSession = Get-Process -Name mstsc $rdpSessionExitedEvent = Register-ObjectEvent -InputObject $rdpSession -EventName Exited -Action {rdpSessionEnd} } function rdpSessionEnd { # To be run when the rdp session has ended or has been aborted by user <Some statements...> } #1. Starting the parent mstsc process using the rdp file parameter. $mstscLauncher = Start-Process -FilePath mstsc -ArgumentList C:\\RDS\\RDS.rdp -PassThru #2. Registering the "exited" event of the "parent" process to run the <registerRdpSessionExitedEvent> function when raised $mstscLauncherExitedEvent = Register-ObjectEvent -InputObject $mstscLauncher -EventName Exited -Action {registerRdpSessionExitedEvent} 

非常感謝 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM