powershellsta

Is Powershell -sta (apartment state) preferred?


I've been dabbling in Powershell (2.0) for the past several months and would love to use it to modernize and standardize some of the processes at work - mostly DOS based processes. Because of the nature of the work, there could be around 100 executions of the same script(s) going at once.

First--Is Powershell "safe" to use in this manner? I have seen -STA as an execution option - is that the preferred method of working with Powershell when executing a good number of the same script simultaneously, or is that something that is only used when absolutely necessary? In my searching, I haven't really come up with an answer for "When should I use apartment state?" I believe most if not all of the scripting I intend to do will not be threaded.

Thanks in advance for anyone who can shed light on Powershell apartment state!


Solution

  • In PSv2, the console host runs as MTA, and the ISE runs as STA. In PSv3 the console defaults to STA.

    You can see what your apartment state is with this:

    [System.Threading.Thread]::CurrentThread.GetApartmentState()
    

    The only time you need to use STA is when using certain classes in .NET that deal with COM objects that use it e.g. System.Windows.Forms.Clipboard.

    There are two ways I know of to change to STA:

    powershell.exe -Sta -File MyScript.ps1
    

    Or

    $ps = [PowerShell]::Create()
    $rs = [RunSpaceFactory]::CreateRunspace()
    $rs.ApartmentState = "STA"
    $rs.ThreadOptions = "ReuseThread"
    $rs.Open()
    $ps.Runspace = $rs
    $ps.AddScript( { ([System.Threading.Thread]::CurrentThread.GetApartmentState()) } ).Invoke()
    

    So the question really is why is the PSv2 console MTA instead of STA? When I want to know why the PS team made decisions like this I usually refer to Bruce Payette's PowerShell in Action book. Unfortunately it didn't say why. It just said there are some COM objects that require STA and if your script doesn't work try re-running it as STA.