4

I have developed a small GUI tool in PowerShell using WPK.

I have the following start up command

powershell -ExecutionPolicy Unrestricted -file PowerTools.ps1 -noexit -sta

I am getting the following error.

New-Object : Exception calling ".ctor" with "0" argument(s): "The calling thread must be STA, because many UI components require this."
At \WindowsPowerShell\Modules\WPK\GeneratedControls\PresentationFramework.ps1:34
10 char:29
+         $Object = New-Object <<<<  System.Windows.Window
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId :     ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

From my Googling, STA stands up "single-threaded apartment", I noticed that that powershell.exe has the "-sta" flag, but that does not help either.

The essence of my ps1 file looks like the following

Import-Module WPK

function get-gui()
{
      New-Window  -WindowStartupLocation CenterScreen `
       -Width 1200 -Height 200 -Show {

      New-Grid -Rows 32, 32, 32, 32 -Columns 110, 200* {
            ...
          }
        }
    }
}

get-gui

Any hints please?

(I did spend quite a bit of time doing my own research)

lingo_journey
  • 653
  • 1
  • 8
  • 22

2 Answers2

4

It it this simple! :) Thanks for your guidance, Kayasax!

powerShell -sta -file PowerTools.ps1
lingo_journey
  • 653
  • 1
  • 8
  • 22
  • Note the difference: I had `powerShell -file PowerTools.ps1 -sta` which didn't work. Can someone explain the difference please? Somehow, my old version has the STA associated with the ps1 file and my new version has STA associated with powershell? – lingo_journey Nov 29 '12 at 13:34
  • 1
    you can check this post, where the script detect if powershell is in sta mode and relaunch it if it is not the case http://powershell-scripting.com/index.php?option=com_joomlaboard&Itemid=76&func=view&id=7157&catid=5#7157 – Loïc MICHEL Nov 29 '12 at 13:39
2

https://technet.microsoft.com/en-us/library/hh847736.aspx says that -file must be last in the in the list of options because everything after the file name is interpreted as parameters to the file. That is why it works when -sta is listed before -file, but does not work after -file.

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
feff
  • 21
  • 1