为我的团队编写脚本,该脚本对url列表进行状态检查。完全虚假的url仍然可以返回200。如果我应该使用else吗?
#Place URL list file in the below path
$sites = Get-Content -Path .\customer_sites.txt
foreach ($site in $sites){
$status = (Invoke-WebRequest -Uri $site -UseDefaultCredentials -AllowUnencryptedAuthentication -
ErrorAction SilentlyContinue).statuscode
switch ($status) {
200 {
Write-Host "Status code $status for site $site ALL GOOD" -ForegroundColor Green
# further action/code specific to code 200 here
}
401 {
Write-Host "Status code $status for site $site SERVER IS UP BUT NO ACCESS" -ForegroundColor Yellow
# further action/code specific to code 404 here
}
default {
Write-Host "Status code $status for site $site ITS DEAD, GO LOOK" -ForegroundColor Red
# further action/code specific to 'other' here
}
}
}
答案 0 :(得分:1)
我认为通过使用-ErrorAction SilentlyContinue
,状态变量将保持其旧值并因此返回“ ALL GOOD”。
更好的方法是将测试放在try..catch
块中。
类似
$sites = Get-Content -Path .\customer_sites.txt
foreach ($site in $sites) {
try{
$response = Invoke-WebRequest $site -UseDefaultCredentials -UseBasicParsing -Method Head -ErrorAction Stop
$status = [int]$response.StatusCode
}
catch {
$status = [int]$_.Exception.Response.StatusCode.value__
}
switch ($status) {
{$_ -ge 100 -and $_ -lt 300} {
Write-Host "Status code $status for site $site ALL GOOD" -ForegroundColor Green
break
}
{$_ -ge 300 -and $_ -lt 400} {
Write-Host "$site is redirected. Statuscode: $status" -ForegroundColor Green
break
}
{$_ -ge 400 -and $_ -lt 500} {
Write-Host "Status code $status for site $site SERVER IS UP BUT NO ACCESS" -ForegroundColor Yellow
break
}
{$_ -ge 500 -and $_ -lt 600} {
Write-Host "Status code $status for site $site ITS DEAD, GO LOOK" -ForegroundColor Red
break
}
default { Write-Host "$site returned an unhandled status code. Statuscode: $status, GO LOOK" -ForegroundColor Red}
}
}