[System.Windows.Forms.MessageBox]::Show doesn't work in PowerShell script

Welcome Forums General PowerShell Q&A [System.Windows.Forms.MessageBox]::Show doesn't work in PowerShell script

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
3 months, 4 weeks ago.

  • Author
    Posts
  • #104660

    Participant
    Points: 43
    Rank: Member

    Hello!

    I have the next PowerShell script:

    …
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms");
    …
    function f
    {
      ….
      try {
         …
      }
      catch {
         [System.Windows.Forms.MessageBox]::Show("Error: $_", "Error","OK","Error");
      }
    
    }
    
    …
    
    

    When I run this script from PowerShell ISE – all works fine, but in PowerShell console I get the error:
    [System.Windows.Forms.MessageBox]::Show("Error...
    Unable to find type [System.Windows.Forms.MessageBox]

    I have tried to add to my script 'Add-Type -AssemblyName System.Windows.Forms', but it didn't give effect – I still get previous error.
    When I enter in PowerShell console 'Add-Type -AssemblyName System.Windows.Forms' before running the my scripts – all also works fine, but it's not decision. Script must run correctly without any preparations.

  • #104680

    Participant
    Points: 165
    Helping Hand
    Rank: Participant

    From what I can see of the script, this should be fine (although that semicolon is unnecessary).

    One alternative you can try is:

    Add-Type -AssemblyName PresentationFramework
    
    [System.Windows.MessageBox]::Show("Error: $_", "Error", "OK", "Error")
  • #104741

    Participant
    Points: 43
    Rank: Member

    One refinement. On my computer with Windows 10 and PowerShell Version 5.1.17134.165 all works fine when I start script from PowerShell console, but on Windows Server 2012 with PowerShell Version 5.1.14409.1012 I still get the previous error.
    Bruce Payette wrote in "Windows PowerShell in Action" about 'using assembly' operator:
    "There was a bug in how using assembly worked; instead of scanning the assembly before it's
    loaded, it defers loading it until runtime. This, unfortunately, makes it exactly useless for its
    intended purpose. Hopefully that bug will be fixed by the time you read this, but if not and you
    see a “type not found” error, at least you'll know why."
    I think I face this bug in my script in not last PowerShell version

The topic ‘[System.Windows.Forms.MessageBox]::Show doesn't work in PowerShell script’ is closed to new replies.