In the previous example we created a small PowerShell function that checks web site availability, and as part of the test results, a HTTP response code was returned. Let’s check out how this numeric code can be easily converted into a meaningful text message.
Here is the function again that tests web sites:
function Test-Url { param ( [Parameter(Mandatory,ValueFromPipeline)] [string] $Url ) Add-Type -AssemblyName System.Web $check = "https://isitdown.site/api/v3/" $encoded = [System.Web.HttpUtility]::UrlEncode($url) $callUrl = "$check$encoded" Invoke-RestMethod -Uri $callUrl | Select-Object -Property Host, IsItDown, Response_Code }
And this would be a typical result:
PS C:\> Test-Url -Url powershellmagazine.com host isitdown response_code ---- -------- ------------- powershellmagazine.com False 200
In this example, the response code is “200” which happens to stand for “OK”. If you’d like to convert HTTP response codes to text, simply convert the data type to [System.Net.HttpStatusCode]. That’s all:
PS C:\> 200 -as [System.Net.HttpStatusCode] OK
Here is a version that incorporates this conversion for you:
function Test-Url { param ( [Parameter(Mandatory,ValueFromPipeline)] [string] $Url ) Add-Type -AssemblyName System.Web $check = "https://isitdown.site/api/v3/" $encoded = [System.Web.HttpUtility]::UrlEncode($url) $callUrl = "$check$encoded" $response = @{ Name = 'Response' Expression = { '{0} ({1})' -f ($_.Response_Code -as [System.Net.HttpStatusCode]), $_.Response_Code } } Invoke-RestMethod -Uri $callUrl | Select-Object -Property Host, IsItDown, $response }
And this would be the result:
PS C:\> Test-Url -Url powershellmagazine.com host isitdown Response ---- -------- -------- powershellmagazine.com False OK (200)
Note how the calculated column “Response” now reports both the original numeric response code and the friendly text for it.