I can run the following PowerShell script "ExampleA.ps1` from a Command Prompt window.
Add-Type -AssemblyName System
Add-Type -AssemblyName System.Windows.Forms
Class MyForm
{
[Object] $theForm
MyForm()
{
$this.theForm = New-Object System.Windows.Forms.Form
}
ShowDialog()
{
$this.theForm.ShowDialog()
}
}
$theForm = New-Object myForm
$theForm.ShowDialog()
The command I used is given below.
powershell -ExecutionPolicy Bypass -File ExampleA.ps1
The result is the form shown below.
I would rather use inheritance in my script. If I do so, I get the script file ExampleB.ps1
shown below.
Add-Type -AssemblyName System
Add-Type -AssemblyName System.Windows.Forms
Class MyForm : System.Windows.Forms.Form
{
}
$theForm = New-Object myForm
$theForm.ShowDialog()
The problem is when I run this script from a Command Prompt window, then I get the following error message.
C:\Users\david\Desktop\test>powershell -ExecutionPolicy Bypass -File ExampleB.ps1
At C:\Users\david\Desktop\test\ExampleB.ps1:3 char:16
+ Class MyForm : System.Windows.Forms.Form
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound
Why can I not inherit System.Windows.Forms.Form`?
The same problem occurs when I try to replace [Object]
with [System.Windows.Forms.Form]
in ExampleA.ps1
. Doing so, produces ExampleC.ps1
shown below.
Add-Type -AssemblyName System
Add-Type -AssemblyName System.Windows.Forms
Class MyForm
{
[System.Windows.Forms.Form] $theForm
MyForm()
{
$this.theForm = New-Object System.Windows.Forms.Form
}
ShowDialog()
{
$this.theForm.ShowDialog()
}
}
$theForm = New-Object myForm
$theForm.ShowDialog()
When I run this script from a Command Prompt window, then I get the following error message.
C:\Users\david\Desktop\test>powershell -ExecutionPolicy Bypass -File ExampleC.ps1
At C:\Users\david\Desktop\test\ExampleC.ps1:5 char:6
+ [System.Windows.Forms.Form] $theForm
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound
Why can I not declare System.Windows.Forms.Form
?
Note: I do realize all three of these scripts run without error from a Windows PowerShell command prompt and from the Windows PowerShell ISE. The problem is that I need to run the scripts from the original Windows Command prompt window.
I am use the current version of 64 bit Windows 10. The output from the $PSVersionTable.PSVersion
command is given below.
Major Minor Build Revision
----- ----- ----- --------
5 1 17134 228