Reputation:
How can you use Get-Variable pipe to operate on specific WinForm objects that match a RegEx to the Fullname property? Attempts to use Where-Object {($_).GetType().FullName -match '^System\.Windows\.Forms'}
fail.
In the example below ($TestButton).GetType().FullName
does return System.Windows.Forms.Button
. But referencing with ($_).GetType().FullName
returns System.Management.Automation.PSVariable
.
Why does this not work, does a near or equivalent exist?
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Remove-Variable * -ErrorAction SilentlyContinue
$form = New-Object system.Windows.Forms.Form;
$form.ClientSize = New-Object System.Drawing.Point(100,100);
$form.text = "Form";
$TestButton = New-Object system.Windows.Forms.Button
$TestButton.text = "Test"
$TestButton.width = 85
$TestButton.height = 30
$TestButton.location = New-Object System.Drawing.Point(0,0)
$TestButton.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',12)
($TestButton).GetType().FullName # This gives output
Get-Variable |
#Where-Object {($_).GetType().FullName -match '^System\.Windows\.Forms'} | # Line disabled for debugging only.
Foreach-Object{
$form.controls.Add($_) # Not working - obvious why due to output below - nothing matches...
($_).GetType().FullName# due to System.Management.Automation.PSVariable
}
$form.controls.AddRange(@($TestButton)) # Works as expected.
[void]$form.ShowDialog()
Upvotes: 0
Views: 134
Reputation: 8868
You could use
Get-Variable | where {$_.Value -is [system.windows.forms.button]}
or
Get-Variable | where {$_.Value.gettype().fullname -match 'system\.windows\.forms'}
Upvotes: 1
Reputation: 801
It does work, just as intended. You're just working with different object types.
$TestButton
is an object of type System.Windows.Forms.Button
When you run Get-Variable
, it returns objects of type System.Management.Automation.PSVariable
if you run Get-Variable -Name TestButton
You'll see that by default, it returns Name and a value field. This is the name of the variable, and the value of said variable.
What I assume you're looking to do, is extract the value of that variable, and get the type of the actual value. You would do this like this
(Get-Variable -Name TestButton | % Value).GetType().Fullname
So for your Get-Variable
pipe
Get-Variable |
Where-Object {$_.value -is [System.Windows.Forms.Button]} |
Foreach-Object{
$form.controls.Add($_.value)
}
Upvotes: 0