PowerShell wait for function call to complete


November 2018


2.7k time


I am calling a series of PowerShell functions from a master script (each function is a test). I specify the tests in an XML file and I want them to run in order.

The functions to call are organized in PowerShell module files (.psm1). The master script calls Import-Module as needed and then calls the function via something like this...

$newResults = & "$runFunction" @ARGS

or this...

$newResults = Invoke-Expression $runFunctionWithArgs

I have gotten both to work just fine and the XML file parsing invokes these commands in the correct order.

Problem: The tests are apparently launched asynchronously so that the first test I launch does not necessarily get invoked and complete before the second test is invoked.

Note, the tests are functions in a PowerShell module and not commands so I do not think that Start-Process will work (but please tell me if you know how to make that work).

More Details: It would take too much to add all the code, but essentially what each function call does is create a hashtable with one or more "TestResult" objects. "TestResult" has things like Success codes and a TimeStamp. Each test does things that take different amounts of time, but all synchronous. I would expect the timestamps to be the same order that I called each test, especially since the first thing each test does is get the timestamp so it should not depend on what the test does. When I run in the ISE, everything goes in order. When I run in the command window, the timestamps do not match my expected order.

Workaround: My working theory is still that PowerShell is somehow parallelizing the calls. I can get consistent results by making the invocation of each call dependent on the results of the previous call. It is a dummy check because I know that what I test will always be true, but PowerShell doesn't know that

if ($newResults.Count -ne [Long]::MaxValue) { $newResults = & "$runFunction" @ARGS }

PowerShell thinks that it needs to know if the previous call count is not MaxValue.

0 answers