Search code examples
powershellnullwebrequesthttpwebresponse

Check for null WebResponseObject


I'm storing the response of an Invoke-WebRequest command in a variable:

$response = Invoke-WebRequest -Uri $URL -Body $body -Headers $headers -Method POST

The API I'm hitting will return null if the processing I'm doing is complete, and I need to check for it:

PS C:\Users\me> Write-Host $response
null

I've tried all the following tests:

If (!$response) {
    Write-Host 'Null 1.'
}
If ($response -eq 'null') {
    Write-Host 'Null 2.'
}
If ($response -eq $null) {
    Write-Host 'Null 3.'
}
If ($response -eq [string]::Empty) {
    Write-Host 'Null 4.'
}
If ($null -eq $response) {
    Write-Host 'Null 5.'
}

None of these work. I know the empty string was a long shot but I figured one of the others should work. What am I doing wrong here?


Solution

  • $response object is a WebResponseObject (or a class that derives from it) and it holds more than just content of a response. That's why the equality checks are failing.

    PS C:\Users\me> Write-Host $response
    

    prints null because Write-Host calls ToString() on the $response object behind the scenes, which returns Content property. Corresponding ToString() implementation is here.

    So the following should work if there is no hidden characters in the response:

    If ($response.Content -eq "null")
    {
      Write-Host "Server returned null"
    }