2016-12-20 29 views
0

我在慢慢地教自己PowerShell,我完全被枚舉困惑。就我的理解而言,它們只是一些真正的整數值的友好名稱集合。好吧,這真是太棒了......但是你如何讓PowerShell真正「看到」它們呢?如何讓PowerShell「查看」.NET枚舉值?

例子:

[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 

這將是巨大的,如果有PowerShell的任何線索 「PictrueBoxSizeMode.StretchImage」 了。 這是一個數值 - 我知道 - 你知道 - 我怎樣才能讓PowerShell知道?

在此先感謝?

+1

'[System.Windows.Forms.PictureBoxSizeMode] :: StretchImage' – TessellatingHeckler

+0

您需要的命名空間,就像任何其他類型。 – SLaks

+2

'$ pictureBox.SizeMode ='StretchImage'' – PetSerAl

回答

0

基礎:

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

高級(含其對應的數字一起名稱):

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

此外,在代碼審查我的回答比較Get-EnumValue功能(自定義cmdlet的)來Getting enum values of Pseudo-Enum classes

編輯

所有上述含在powershell_ise[System.Windows.Forms.PictureBoxSizeMode]運行代碼。不幸的是,powershell提高TypeNotFound錯誤:

 
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 

我們需要再次向System.Windows.Forms命名空間的引用;一些消息來源勸續訂參考System.Drawing還有:

 
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> 
+0

是的,我知道允許的值*是什麼* - 我只是無法讓PowerShell將「StretchImage」變成任何它應該是的數值。 –

+0

@EdChandler答案已更新。 – JosefZ