PowerShell Quick Tip: Determine STA Threading Mode
Posted by Trevor Sullivan on 2010/11/02
Some code in PowerShell requires you to use the Single-Threaded Apartment (STA) threading model. The PowerShell version 2.0 console host uses Multi-Threaded Apartment by default. The PowerShell Integrated Scripting Environment (ISE) uses the STA threading model.
If you’re writing code using the WPK module included in the PowerShellPack, you will need to ensure that you are using the STA model. You can avoid errors in your code by adding a check for the threading model before you attempt to run WPK code. Here is a simple, one-line example of how to do that:
[System.Management.Automation.Runspaces.Runspace]::DefaultRunspace.ApartmentState -eq [Threading.ApartmentState]::STA
What the above code does is:
- Gets the current (default) Runspace
- Looks at the ApartmentState property, whose value is an ApartmentState
- Compares it to the STA
Note: It’s important to note that, in testing, I discovered that when the threading state is set to MTA in the PowerShell console host, the Runspace.ApartmentState property is set to [Threading.ApartmentState]::Unknown. I don’t know why this is, but keep it in mind if you’re planning on performing a comparison against [Threading.ApartmentState]::MTA – this simply won’t work for the MTA model in PowerShell, unless someone else has a different experience than me.