Hello,
I found this nice forum after I was shocked to find that questions were no longer possible in the MS Powershell Technet forum. Hope someone here can help me.
I would like to specify a variable in a text field in a winform. This should then update automatically in winform. First, a WMI event is registered, which checks whether a USB device is connected or not. The result is stored in the $Global:ConnectionStatus variable. This also works, the variable changes as soon as a USB device is connected or not. The initial entry of the status in Winform also works. Just don’t update it.
Script:(Should work everywhere).
###Register event to watch changing usb drives
#Query for finding all device arrival events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"
#Register an event subscription
Register-WmiEvent -Query $query -Action {
$volumeName = (Get-WMIObject -Class Win32_LogicalDisk -Filter "DeviceID='$($Event.SourceEventArgs.NewEvent.DriveName)'").VolumeName
$Global:ConnectionStatus = "Laufwerk $volumeName verbunden"
} | Out-Null
#Query for finding all device Removal events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=3"
#Register an event subscription
Register-WmiEvent -Query $query -Action {
$Global:ConnectionStatus = 'Nicht verbunden'
} | Out-Null
#region windows forms
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
#
#Create main form
#
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border, not able to resize
$Form.Text = "Test"
$Form.Size = New-Object System.Drawing.Size(946, 580)
$Form.StartPosition = "CenterScreen"
$Form.AutoScroll = $True
$Form.AutoSize = $True
$Form.AutoSizeMode = "GrowOnly" #GrowAndShrink or GrowOnly
$Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 12)
$Form.Font = $Font
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#
#Create textbox
#
$Textbox1Connection = New-Object 'System.Windows.Forms.TextBox'
$Textbox1Connection.Font = [System.Drawing.Font]::new('Microsoft Sans Serif', '9.75')
$Textbox1Connection.Location = New-Object System.Drawing.Size(36, 45)
$Textbox1Connection.Size = New-Object System.Drawing.Size(180, 22)
$Textbox1Connection.Text = "$Global:ConnectionStatus"
$textbox1Connection.TextAlign = 'Center'
$Textbox1Connection.ReadOnly = $True
$Form.Controls.Add($Textbox1Connection)
#Activate the form
$Form.Add_Shown({$Form.Activate()})
[void]$Form.ShowDialog()
#Unregister event
#Get-EventSubscriber | Unregister-Event