Search code examples
powershellbatch-filecmdmessagebox

How to execute PowerShell Net MessageBox in cmd/batch


I have a batch file with lot of stuff. I there is one Alert Window with info for user.

On Windows Pro I'm using Msg command for it and it works fine.

On Windows Home there is no Msg, so I got the idea to use PowerShell instead:

[System.Windows.Forms.MessageBox]::Show("my text")

which works fine in PowerShell.

-However, when I try to use it in batch or execute it directly in Cmd, I only get the text:

  C:\Windows\System32>powershell {[System.Windows.Forms.MessageBox]::Show("\""my text"\"")}
    [System.Windows.Forms.MessageBox]::Show("my text")

Or I get errors:

C:\Windows\System32>powershell -command [System.Windows.Forms.MessageBox]::Show("my text")
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+                                         ~
Missing ')' in method call.
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+                                         ~~
Unexpected token 'my' in expression or statement.
At line:1 char:48
+ [System.Windows.Forms.MessageBox]::Show(my text)
+                                                ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

or

     C:\Windows\System32>powershell -command "& {[System.Windows.Forms.MessageBox]::Show('my text')}"
Unable to find type [System.Windows.Forms.MessageBox].
At line:1 char:4
+ & {[System.Windows.Forms.MessageBox]::Show('my text')}
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Windows.Forms.MessageBox:TypeName) [],
    RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

What should I do to get it to work?

(without rewriting the whole script to PowerShell, that is)


Solution

  • You need to load the type before you can invoke it. You can do this:

    powershell -command "[reflection.assembly]::LoadWithPartialName('System.Windows.Forms')|out-null;[windows.forms.messagebox]::Show('my message')"