@@ -331,6 +331,7 @@ function Invoke-RemoteScript {
331331 }
332332
333333 [System.Net.HttpWebResponse ]$script :errorResponse = $null
334+ $script :encounteredError = $false
334335
335336 $response = & {
336337 try {
@@ -346,10 +347,24 @@ function Invoke-RemoteScript {
346347 $content.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue(" text/plain" )
347348 $content.Headers.ContentEncoding.Add (" gzip" )
348349
349- $taskResult = $client.PostAsync ($url , $content ).Result
350- $taskResult.EnsureSuccessStatusCode () > $null
351- $taskResult.Content.ReadAsStringAsync ().Result
352- Write-Verbose - Message " Script transfer complete."
350+ $postResponse = $client.PostAsync ($url , $content )
351+ $taskResult = $postResponse.Result
352+ if ($taskResult ) {
353+ $taskResult.EnsureSuccessStatusCode () > $null
354+ $taskResult.Content.ReadAsStringAsync ().Result
355+ Write-Verbose - Message " Script transfer complete."
356+ } else {
357+ $script :ex = $postResponse.Exception
358+ $reason = $postResponse.Exception.Message
359+ $innerException = $postResponse.Exception
360+ while (($innerException = $innerException.InnerException )) {
361+ $reason += " " + $innerException.Message
362+ }
363+ $script :encounteredError = $true
364+ Write-Error - Message " Server response: $ ( $reason ) " - Category ConnectionError `
365+ - CategoryActivity " Post" - CategoryTargetName $uri - CategoryReason " $ ( $postResponse.Status ) " - CategoryTargetType $RootPath - ErrorAction SilentlyContinue
366+ $Host.UI.WriteErrorLine ($reason )
367+ }
353368 }
354369 catch [System.Net.Http.HttpRequestException ] {
355370 $script :ex = $_.Exception
@@ -369,12 +384,17 @@ function Invoke-RemoteScript {
369384 }
370385
371386 if ($errorResponse ) {
387+ $script :encounteredError = $true
372388 Write-Error - Message " Server response: $ ( $errorResponse.ReasonPhrase ) " - Category ConnectionError `
373389 - CategoryActivity " Download" - CategoryTargetName $uri - Exception ($script :ex ) - CategoryReason " $ ( $errorResponse.StatusCode ) " - CategoryTargetType $RootPath
374390 }
375391
376- Write-Verbose - Message " Parsing response from server."
377- Parse- Response - Response $response - HasRedirectedMessages $hasRedirectedMessages - Raw $Raw
392+ if (! $encounteredError ) {
393+ Write-Verbose - Message " Parsing response from server."
394+ Parse- Response - Response $response - HasRedirectedMessages $hasRedirectedMessages - Raw $Raw
395+ } else {
396+ Write-Verbose - Message " Stopping from further execution."
397+ }
378398 }
379399 }
380400}
0 commit comments