根据应用用户的名称检测应用关闭

时间:2015-08-05 10:18:48

标签: powershell crash windows-applications

一直在尝试创建脚本来检测用户的应用程序崩溃。 (假设计算机由多个用户使用)

到目前为止,只能设法在代码下方查询应用程序(仅基于用户名),但不会关闭应用程序或崩溃

gwmi -query "select * from win32_process where name='calc.exe'" | %{if($_.GetOwner().User -eq 'myUser'){
    #do something when app crash
}}

1 个答案:

答案 0 :(得分:0)

您可以使用Register-WmiEvent cmdlet向Win32_ProcessStopTrace事件类注册事件。

Win32_ProcessStopTrace没有GetOwner()方法,但您可以使用当前代码收集您感兴趣的流程的流程ID,并在事件查询中使用它们:

$UserName = 'myUser'
$ProcessName = 'calc.exe'
$PIDFilters = Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='$ProcessName'" |Where-Object {
    $_.GetOwner().User -eq $UserName
} |Select-Object -ExpandProperty ProcessId |ForEach-Object {
    "ProcessId={0}" -f $_
}

$WmiFilter = $PIDFilters -join " OR "

现在,你有$WmiFilter看起来像这样:

ProcessId=2468 OR ProcessId=11576 OR ProcessId=5426

您可以在WMI查询中使用它:

$WmiQuery = "SELECT * FROM Win32_ProcessStopTrace WHERE ($WmiFilter)"

最后用Register-WmiEvent注册活动:

Register-WmiEvent -Query $WmiQuery -SourceIdentifier CalcStopEvent -Action {
    $TraceEvent = $Event.SourceEventArgs.NewEvent
    if($TraceEvent.ExitStatus -ne 0){
        # The process didn't exit with success/noerror
        # Send many emails!
        # Sound the klaxon!
        # Call the fire brigade!
        # or, whatever you feel like ...
    }
}