1

All

I'm new to powershell and I'm trying to write a class with pop out the message box while something wrong. It looks like when in the class the powershell cannot find the type of [System.Windows.Forms.MessageBox], meanwhile, the parameter type also cannot recognize the [System.Windows.Forms.xxxx]. How can I solve this issue? Here is some sample code below.And I also got the error messages in vscode as listed.Any help from you are appreciated!

Sample Code

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore,PresentationFramework
Class Test
{
    [System.Windows.Forms.Form]$form

    Test()
    {
        [System.Windows.Forms.MessageBox]::Show("Class Created!","Info","OK","Info")|Out-Null
    }
}
[Test]::new()

ERROR MESSAGES

[Running] powershell -ExecutionPolicy ByPass -File "c:\PowerShell\tempCodeRunnerFile.ps1"
At C:\PowerShell\tempCodeRunnerFile.ps1:7 char:6
+     [System.Windows.Forms.Form]$form
+      ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
At C:\PowerShell\tempCodeRunnerFile.ps1:11 char:10
+         [System.Windows.Forms.MessageBox]::Show("Class Created!","Inf ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.MessageBox].
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TypeNotFound
 

[Done] exited with code=1 in 0.409 seconds

PS-VERSION-TABLE

PS C:\PowerShell> $PSversiontable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1320
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.1320
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
Robin Hoo
  • 11
  • 1
  • 1
  • In short: You're trying to use `Add-Type`-added .NET types in the context of a PowerShell custom [class](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Classes) defined in the same file. Unfortunately, this isn't supported as of PowerShell 7.2, because any .NET types referenced in `class` definitions must have been loaded _beforehand_. See the [linked duplicate](https://stackoverflow.com/questions/34625440/using-net-objects-within-a-powershell-v5-class) for workarounds and potential future improvements. – mklement0 Dec 28 '21 at 01:56
  • Thanks mklement0! It's really helpful! However, I gave up my thoughts on coding in OOP powershell. Too many restrictions. – Robin Hoo Dec 28 '21 at 06:30

0 Answers0