diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index d01c52a655..4d76a6c3ca 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -146,11 +146,12 @@ function GetTestData Describe "Invoke-WebRequest tests" -Tags "Feature" { BeforeAll { - $null = Start-HttpListener -AsJob -Port 8080 + $response = Start-HttpListener -Port 8080 } AfterAll { $null = Stop-HttpListener -Port 8080 + $response.PowerShell.Dispose() } # Validate the output of Invoke-WebRequest @@ -576,11 +577,12 @@ Describe "Invoke-WebRequest tests" -Tags "Feature" { Describe "Invoke-RestMethod tests" -Tags "Feature" { BeforeAll { - $null = Start-HttpListener -AsJob -Port 8081 + $response = Start-HttpListener -Port 8081 } AfterAll { $null = Stop-HttpListener -Port 8081 + $response.PowerShell.Dispose() } It "Invoke-RestMethod returns User-Agent" { diff --git a/test/tools/Modules/HttpListener/HttpListener.psm1 b/test/tools/Modules/HttpListener/HttpListener.psm1 index 1d6a795d26..becb21ac80 100644 --- a/test/tools/Modules/HttpListener/HttpListener.psm1 +++ b/test/tools/Modules/HttpListener/HttpListener.psm1 @@ -37,7 +37,7 @@ Function Start-HTTPListener { [Int] $Port = 8080, [Parameter()] - [switch] $AsJob + [switch] $Foreground ) Process { @@ -214,19 +214,36 @@ Function Start-HTTPListener { $response.Close() } } + catch + { + $errormsg = $_ | convertto-json + Write-Error $errormsg + } finally { $listener.Stop() + Write-Information "Listener is stopped" -InformationAction Continue } } - if ($AsJob) - { - Start-Job -ScriptBlock $script -ArgumentList $Port - } - else + if ($Foreground) { & $script -Port $Port } + else + { + $ps = [powershell]::Create() + $null = $ps.AddScript($script) + $null = $ps.AddParameter("port",$port) + $AsyncResponse = $ps.BeginInvoke() + # include the AsyncResponse in the return object + # it can be used to determine whether execution + # is still underway, and may be useful in debugging + # if something goes amiss + [pscustomobject]@{ + PowerShell = $ps + AsyncResponse = $AsyncResponse + } + } } }