0

I'm trying to create a script that has no window (it runs on the systray) and I want to execute some code every time a new process is created in the system

# Add assemblies for WPF and Mahapps - see https://www.systanddeploy.com/2018/12/create-your-own-powershell.html
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName WindowsFormsIntegration
# [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')    | out-null
# [System.Reflection.Assembly]::LoadWithPartialName('presentationframework')   | out-null
# [System.Reflection.Assembly]::LoadWithPartialName('System.Drawing')          | out-null
# [System.Reflection.Assembly]::LoadWithPartialName('WindowsFormsIntegration') | out-null

$global:WshShell = New-Object -comObject WScript.Shell
$query = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'"
$action = {
    $e = $Event.NewEvent.TargetInstance
    Write-Host "New process event: ${e.Name}"
}
Register-CimIndicationEvent -Query $query -SourceIdentifier "ProcessWatcher" -Action $action

# Add the systray icon
$global:mainIcon = New-Object System.Windows.Forms.NotifyIcon
$mainIcon.Text = "Test Events"
$mainIcon.Icon = $icon
$mainIcon.Visible = $true

# Comment out to debug why the event is not firing
# $windowcode = '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);'
# $asyncwindow = Add-Type -MemberDefinition $windowcode -name Win32ShowWindowAsync -namespace Win32Functions -PassThru
# $null = $asyncwindow::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0)

Write-Host started

$ctx = New-Object System.Windows.Forms.ApplicationContex
[void][System.Windows.Forms.Application]::Run($ctx)

The action isn't firing no matter what. I've tried the event part and it works on its own. It's like when I call Run the whole WMI event registration "expires" somehow or gets out of context and gets destroyed. I've tried creating a file as the action of an event but it does not do that either.

dzervas
  • 250
  • 2
  • 14
  • [Win32_ProcessTrace](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/krnlprov/win32-processtrace) -- Similar, using `ManagementEventWatcher`: [How do I get information about recently connected USB device?](https://stackoverflow.com/a/54298316/7444103) – Jimi Nov 24 '22 at 13:39

0 Answers0