PowerShell script, чтобы проверить статус URL-адреса
Подобно этому вопросу здесь Я пытаюсь отслеживать, работает ли набор ссылок на веб-сайт или не отвечает. Я нашел тот же PowerShell script через Интернет.
Однако вместо прямых ссылок на сайт мне нужно проверить более конкретные ссылки, например:
http://mypage.global/Chemical/
http://maypage2:9080/portal/site/hotpot/
Когда я пытаюсь проверить состояние этих ссылок, я получаю следующий вывод:
URL StatusCode StatusDescription ResponseLength TimeTaken
http://mypage.global/Chemical/ 0
http://maypage2:9080/portal/site/hotpot/ 0
Приведенные выше ссылки требуют, чтобы я был подключен к VPN, но я могу получить доступ к этим ссылкам из браузера.
Вывод Invoke-WebRequest -Uri https://stackoverflow.com/info/20259251/powershell-script-to-check-the-status-of-a-url
:
PS C:\Users\682126> Invoke-WebRequest -Uri https://stackoverflow.com/info/20259251/powershell-script-to-check-the-status-of-a-url
The term 'Invoke-WebRequest' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:18
+ Invoke-WebRequest <<<< -Uri https://stackoverflow.com/info/20259251/powershell-script-to-check-the-status-of-a-url > tmp.txt
+ CategoryInfo : ObjectNotFound: (Invoke-WebRequest:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
$PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.5472
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Ответы
Ответ 1
Недавно я создал script, который делает это.
Как указал Дэвид Брабант, вы можете использовать класс System.Net.WebRequest
для выполнения HTTP-запроса.
Чтобы проверить, работает ли он, вы должны использовать следующий пример кода:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
$HTTP_Response.Close()
Ответ 2
Для людей с PowerShell 3 или более поздней версией (например, Windows Server 2012+ или Windows Server 2008 R2 с обновление для Windows Management Framework 4.0), вы можете сделать это однострочное выражение вместо вызова System.Net.WebRequest
:
$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}
Ответ 3
$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')
$response = $request.GetResponse()
$response.StatusCode
$response.Close()
Ответ 4
Вы можете попробовать следующее:
function Get-UrlStatusCode([string] $Url)
{
try
{
(Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
}
catch [Net.WebException]
{
[int]$_.Exception.Response.StatusCode
}
}
$statusCode = Get-UrlStatusCode 'httpstat.us/500'