2

There is some Power Shell script that returns content.

and it is called using the Powershell Web API:

Invoke-WebRequest -Headers $headers -Uri $CMHostname/-/script/v2/master/Get-TestContent?type=AllItems

Case 1

try
{
....
} catch {
   Write-Host "Error: $_"
   exit 402
   # return 402
}

it is always returns HTTP code 200

Case 2  script like below, always return HTTP 500 and content  'The page cannot be displayed because an internal server error has occurred.'

try
{
....
 throw "some error"
} catch {
   Write-Host "Error: $_"
   throw $_
}

Is it possible to return a specific HTTP code?

1

4 Answers 4

0

Can you use something like the following inside your Get-TestContent script?

if ($HttpContext){
    $HttpContext.Response.StatusCode = 201
}
2
  • Coll thanks, to provide custom error text need to use 201 status code - other HTTP codes rewrite content (error text) Commented Apr 9 at 12:13
  • 1
    so the final solution is: ``` catch { Write-Host "Error: $_" $context = [System.Web.HttpContext]::Current if ($context) { $context.Response.StatusCode = 201 } } ``` Commented Apr 9 at 12:14
1

Thank you, Michael West

final solution for me:


catch
{
   Write-Host "Error: $_"
   $context = [System.Web.HttpContext]::Current
   if ($context)
   {
        $context.Response.StatusCode = 201
   }
}

0

You can get the response status code in the try catch block using $_.Exception Object.

try
{  
  $response = Invoke-WebRequest -Uri $uri -UseBasicParsing
  Write-Host $response.StatusCode
}
catch 
{
  [int]$StatusCode = $_.Exception.Response.StatusCode
  $errorMessage = $_.Exception.Message
  Write-Host $StatusCode
  Write-Host $errorMessage
}

This returns the output in the following format:

enter image description here

Hope this helps!!!

0

The following information might be useful for you to call Invoke-WebRequest and get the response details.

You need to catch the exception and then get the response stream from Response like below.

try
{
    $response = Invoke-RestMethod Method Get uri "$($uri)" -Headers $headers
    return $response
}
catch
{
    Write-Host "Exception details: "
    $e = $_.Exception
    Write-Host ("`tMessage: " + $e.Message)
    Write-Host ("`tStatus code: " + $e.Response.StatusCode)
    Write-Host ("`tStatus description: " + $e.Response.StatusDescription)

    Write-Host "`tResponse: " -NoNewline
    $memStream = $e.Response.GetResponseStream()
    $readStream = New-Object System.IO.StreamReader($memStream)
    while ($readStream.Peek() -ne -1) {
        Write-Host $readStream.ReadLine()
    }
    $readStream.Dispose();
}

Hope this will give you all the details of the response that you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.