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.
source share