Im trying to write a script which loops trough a CSV File with a bunch of links in it. Then i want to check with Invoke-WebRequest if the page is reachable. This works fine if the HTTP response code is "200". But I also want the script to write out the response code when it is somewhat like 4xx, 3xx, 5xx etc. So far the response code variable is just empty.
The problem is that when ''Invoke-WebRequest'' returns not 200(thats kinda the point of the script) it generates an error instead of giving me a clean output with the HTTP Response Code.
My script so far:
$Links = Import-Csv -Path 'Path\to\file.csv' -Delimiter ";"
$user = Get-Credential
function Check-Link{
$name_de = $Link.title_de
$link_de = $Link.url_de
Write-Host $link_de
$HTTP_Response = (Invoke-WebRequest $Link.url_de -Credential $user -Method Head).StatusCode
if($HTTP_Response -ne 200){
Write-Host "The page $name_de is not reachable! Response Code: $HTTP_Response"
}
else{
Write-Host "The page $name_de is reachable!"
}
}
$DeadLinks
foreach($Link in $Links){
Check-Link
Start-Sleep 10
}
Now when the Response code does NOT equal 200 the output ist:
www.example.com
the page example.com is not reachable! Response Code:
The expected output would be:
www.example.com
the page example.com is not reachable! Response Code: 401