Ed Chandler
Ed Chandler

Reputation: 71

How do you get PowerShell to "see" .NET enum values?

I'm slowly teaching myself PowerShell and I'm completely baffled by enums. To my understanding, they're just a collection of friendly names for what are really integer values. Okay, ... that's great ... but how do you get PowerShell to actually "see" them?

Example:

[System.Windows.Forms.Application]::EnableVisualStyles();
$form = new-object Windows.Forms.Form
$form.Text = "Image Viewer"
$form.Width = $img.Size.Width;
$form.Height =  $img.Size.Height;
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Width =  $img.Size.Width;
$pictureBox.Height =  $img.Size.Height;
$pictureBox.SizeMode = PictureBoxSizeMode.StretchImage

This would be great if PowerShell had any clue what "PictrueBoxSizeMode.StretchImage" was. It's a numeric value -- I know that -- you know that -- how do I get PowerShell to know that?

Thanks in advance?

Upvotes: 2

Views: 5330

Answers (1)

JosefZ
JosefZ

Reputation: 30113

Basic:

[System.Windows.Forms.PictureBoxSizeMode].GetEnumNames()

Advanced (names along with their numeric equivalents):

[System.Enum]::GetNames([System.Windows.Forms.PictureBoxSizeMode])|
    ForEach-Object {"{0} {1}" -f 
        [System.Windows.Forms.PictureBoxSizeMode]::$_.value__, $_ }

Also compare Get-EnumValue function (custom cmdlet) in my answer to Getting enum values of Pseudo-Enum classes at Code Review.

Edit

All above code containing [System.Windows.Forms.PictureBoxSizeMode] run in powershell_ise. Unfortunately, powershell raises TypeNotFound error:

PS D:\PShell> [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
Unable to find type [System.Windows.Forms.PictureBoxSizeMode]. Make sure that the assembly that contains this type is loaded. At line:1 char:1
+ [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Windows.Forms.PictureBoxSizeMode:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

We need to renew a reference to System.Windows.Forms namespace; some sources advise renewing a reference to System.Drawing as well:

PS D:\PShell> [void] (Add-Type -AssemblyName System.Windows.Forms -PassThru)
PS D:\PShell> [void] (Add-Type -AssemblyName System.Drawing -PassThru)
PS D:\PShell> [System.Windows.Forms.PictureBoxSizeMode]::StretchImage
StretchImage
PS D:\PShell> [System.Windows.Forms.PictureBoxSizeMode]::StretchImage.value__
1
PS D:\PShell>

Upvotes: 3

Related Questions