首页 > 解决方案 > 如何编写powershell脚本以根据其他网站url获取网站url的状态

问题描述

有人可以帮忙吗!

使用下面的 Power Shell 脚本,我可以获得所有 URL 的状态。有了这个,虽然谷歌 URL 不起作用(我故意给出了错误的 url),但脚本运行了 3 次,这是没有用的。

我的条件是……我的 gmail 和登录链接只有在 google 链接有效时才有效。我的登录链接只有在 gmail 链接有效时才有效。如果没有,它应该通过发送带有错误代码的电子邮件来结束脚本(我正在使用这个 try catch 块来存储这个错误代码)。

这是我的代码。

$ErrorActionPreference = "Stop"

[array]$URL_LIST_FILE = Get-Content -Path 'path/of/file'

$URL_LIST = @($URL_LIST_FILE)
foreach ($URL in $URL_LIST)
{
    try {
        $RESPONSE = Invoke-WebRequest -URI $URL -ErrorAction Stop
        $RESPONSE_CODE = $RESPONSE.Statuscode
        Write-Host "Response Code: $RESPONSE_CODE" -ForegroundColor Green
        if ($RESPONSE_CODE -eq 200)
        {
            Write-Host "$URL is Working." -ForegroundColor Blue
        }
    }
    catch {
        $ERR = $_.Exception.Response.StatusCode
        $ERR_CODE = $_.Exception.Response.StatusCode.value__ 
        Write-Host $ERR_CODE $ERR -ForegroundColor Red
        Write-Host "$URL is not working. Sending Email..." -ForegroundColor Yellow
        #Send-MailMessage -To to@somemail.com -From from@somemail.com -Subject "subject is here" 
    }
}

我的文件包含:

www.google.com                        - Google link
www.gmail.com                         - Gmail link
www.accounts.google.com/gmail         - Signin link
...
...
...

标签: windowspowershellpowershell-3.0azure-powershellpowershell-4.0

解决方案


尝试在 else 语句中捕获错误。

if ($RESPONSE_CODE -eq 200)
        {
            Write-Host "$URL is Working." -ForegroundColor Blue
        }
Else {Write-Host "$URL is not Working." -ForegroundColor red}

推荐阅读