David Anderson
David Anderson

Reputation: 1158

Execute a PowerShell script from a Windows command prompt

I have the current version of 64 bit Windows 10 installed.

I can open a Windows PowerShell window and enter the following command to execute my PowerShell script. The script execute without error.

PS C:\Users\david\Desktop\test> ./messagebox.ps1

I want to execute the same script from a Windows Command Prompt window. When I enter the follow command, I get the displayed error messages.

C:\Users\david\Desktop\test>powershell -ExecutionPolicy Bypass -file messagebox.ps1
At C:\Users\david\Desktop\test\messagebox.ps1:81 char:14
+ Class Form : System.Windows.Forms.Form
+              ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
At C:\Users\david\Desktop\test\messagebox.ps1:102 char:21
+             return [System.Windows.Forms.MessageBox]::Show($messsage, ...
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.MessageBox].
At C:\Users\david\Desktop\test\messagebox.ps1:108 char:21
+             return [System.Windows.Forms.MessageBox]::Show($messsage, ...
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.MessageBox].
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TypeNotFound

The script includes the following lines which I thought would include the correct assembly.

$n = new-object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[System.AppDomain]::CurrentDomain.Load($n) | Out-Null

Upvotes: 0

Views: 231

Answers (1)

Kory Gill
Kory Gill

Reputation: 7153

You did not post enough code to actually reproduce the issue, but this works for me:

Add-Type -AssemblyName System.Windows.Forms | Out-Null
[System.Windows.Forms.MessageBox]::Show("Hello World")

I assume you can extend this to whatever version of Show() you need.

See also PowerShell Magazine

Upvotes: 2

Related Questions