Is Powershell -sta (apartment condition) expected?

I have been working in Powershell (2.0) for the past few months and would like to use it to modernize and standardize some processes at work - mainly DOS-based processes. Due to the nature of the work, there may be about 100 executions of the same script (s) at the same time.

First: “Is it safe to use Powershell” this way? I saw -STA as an implementation option - is it the preferred method of working with Powershell while running a large number of the same scripts, or is it only used when it is absolutely necessary? In my search, I actually have no answer: "When should I use the state of the apartment?" I believe that most, if not all of the scenarios that I intend to do will not be permeated.

Thanks in advance to anyone who can shed light on the condition of Powershell Apartments!

+6
source share
1 answer

In PSv2, the console host acts as an MTA, and ISE acts as an STA. In PSv3, the console defaults to STA .

You can see what is the condition of your apartment:

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

The only time you need to use STA is to use certain classes in .NET that deal with COM objects that use it, for example. System.Windows.Forms.Clipboard .

There are two ways to change the 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 real question is, why is the MTA PSv2 console instead of the STA? When I want to know why the PS team made such decisions, I usually refer to Bruce Payette PowerShell in an action book. Unfortunately, he did not say why. He simply said that there are some COM objects that require an STA, and if your script does not work, try restarting it as an STA.

+9
source

All Articles