Is it possible to manage WMI events though space and main form?

I am trying to create a background worker that will scan for USB device changes.

I find it difficult to work with WMI audit events outside of the workspace. Basically, when I close the window (AKA form), I would like to cancel Wait-Event

. But I can't control this from the run side, so it gets stuck. Is it possible?

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form1 = New-Object System.Windows.Forms.Form
$form1.Text = "My PowerShell Form"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1400
$System_Drawing_Size.Height = 600
$form1.ClientSize = $System_Drawing_Size

$Global:x = [Hashtable]::Synchronized(@{})
$x.Host = $Host
$x.Flag = $true

$rs = [RunspaceFactory]::CreateRunspace()
$rs.ApartmentState, $rs.ThreadOptions = "STA", "ReUseThread"
$rs.Open()
$rs.SessionStateProxy.SetVariable("x",$x)
$cmd = [PowerShell]::Create().AddScript({
    Register-WmiEvent -Class Win32_DeviceChangeEvent -SourceIdentifier volumeChange
    do {
        $retEvent = Wait-Event -SourceIdentifier volumeChange
        Remove-Event -SourceIdentifier volumeChange
    } while ($x.Flag) #Loop until next event

    Unregister-Event -SourceIdentifier volumeChange
})
$cmd.Runspace = $rs
$handle = $cmd.BeginInvoke()

$OnClosing = {
    $x.Flag = $false
    $x.Host.UI.WriteVerboseLine($x.Flag)

    $cmd.EndInvoke($handle)
}

$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.Add_Load($OnLoadForm_StateCorrection)
$form1.Add_Closing($OnClosing)
$form1.ShowDialog() | Out-Null

      

+2


source to share





All Articles