Test Automation with Windows PowerShell and STA vs. MTA

Bummer. I’ve been experimenting with test automation using Windows PowerShell. Everything was wonderful until last week; I performed proof-of-concept demonstrations for almost all of the key test automation tasks including API testing, low-level (via Win32) Windows application UI testing, HTTP request-response testing, low-level (via COM and the IE DOM) Web application UI testing, Web Services testing, and so on. I found that PowerShell is very well-suited for all the test automation tasks I investigated. Then I looked at what I presumed would be by far the easiest type of automation with PowerShell, Windows application UI test automation via the Micosoft UI Automation (MUIA) library/framework. Why did I think this would be trivial? Because PowerShell is essentially a text-based .NET application and therefore all I would be doing is calling code in a .NET Framework library (the MUIA lib that is) from a .NET application (i.e., PowerShell). What could possibly go wrong? Well, as it turns out, the MUIA library employs COM interop to call into Win32 functions such as FindWindow() and SendMessage(). Whenever you use COM interop you must use either a single-thread approach, which ultimately calls the CoInitialize() function, or a multithreaded approach which ultimately calls the CoInitializeEx() function. The MUIA library apparently uses a simple STA (single-threaded apartment) model but unfortunately PowerShell makes all calls using a MTA (multi-threaded apartment model). The effect is that calling certain MUIA library methods from PowerShell just doesn’t work. I speculate that PowerShell uses multiple threads; one of these threads calls into the MUIA library; the MUIA library uses a single thread which requires no synchronization plumbing to call into an underlying COM object which actually provides the automation functionality; the return bubbles back up to PowerShell but either returns on a different PowerShell thread or simply gets lost somehow because of the differences between the MUIA library STA and the PowerShell MTA. Bummer. 
This entry was posted in Software Test Automation. Bookmark the permalink.

2 Responses to Test Automation with Windows PowerShell and STA vs. MTA

  1. Marco says:

    Check this post for the invoke-apartment cmdlet source code (in C#) that lets you create an STA thread from within PowerShell:
    This is apparently built-into the v2 CTP, but I haven\’t found the time to figure out how to invoke it.

  2. Unknown says:

    So funny.  I just took your class on powershell. 🙂 Hi james. 

Comments are closed.