小编JST*_*JST的帖子

如果用户单击"关闭"("X")按钮,如何处理PowerShell窗口的关闭事件

我想在PowerShell 2.0窗口关闭之前运行一些代码.为此,我试过:

PS> register-engineevent PowerShell.Exiting -action {get-process | out-file c:\ work\powershellexiteventcalled.txt}

如果用户使用exit命令关闭PowerShell窗口(即退出),它可以正常工作.但是如果用户通过点击右上角的关闭('X')按钮关闭它,它就不起作用.

我找不到办法解决这个问题.我也尝试过以下方式,但这也不起作用:

PS> $ query ="选择*来自__InstanceDeletionEvent WITHIN 5 WHERE TargetInstance ISA'Win32_Process'AND TargetInstance.Name ='powershell.exe'"

PS> Register-WmiEvent -Query $ query -Action {get-process | out-file c:\ work\powershellexiteventcalled.txt}

请指导我如何完成这项任务.


更新:通过一个有用的专业在线的一些有用的输入我也尝试了以下:

$ appCurrentDomain = [System.AppDomain] :: CurrentDomain Register-ObjectEvent -Action {get-process | out-file c:\ work\powershellexiteventcalled.txt} -InputObject $ appCurrentDomain -EventName DomainUnload

但同样,它不起作用.根据Microsoft"当AppDomain即将被卸载时发生DomainUnload事件." 但是当我关闭窗口时它不起作用(或者甚至键入exit).

更新:

在其他专业人士的帮助下,我可以通过以下代码实现这一目标.

PS..> $code = @"

        using System;
        using System.Runtime.InteropServices;
        using System.Management.Automation;
        using System.Management.Automation.Runspaces;

        namespace MyNamespace
        {
            public static class MyClass
            { …
Run Code Online (Sandbox Code Playgroud)

powershell

8
推荐指数
1
解决办法
6761
查看次数

标签 统计

powershell ×1