在Powershell中返回大文件的url和状态代码

时间:2019-03-28 20:40:50

标签: powershell csv https status

我修改了一个大文件,只给我要在Powershell中运行以检查状态代码并返回它们的URL。我是Powershell的新手,所以我的代码有一些问题。该文件也可能有重复的网址。

当我只插入一个URL时,我就可以正常工作了。我为each Object尝试了一些不同的操作,但感觉好像很接近。

$urlArray = Import-Csv -Path "Scripts\test.csv" | Select -ExpandProperty urls


Function Get-WebStatus($url){

foreach ($url in $urlArray) {
    # First we create the request.
    $HTTP_Request = [System.Net.WebRequest]::Create($url)

    # 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 $url + $HTTP_Request
    }
}
}

我只需要一个无效站点列表。最好将其保存到自己的txt文件中。

不起作用的示例: google.com 404

2 个答案:

答案 0 :(得分:1)

这应该有效:

Add-Type -AssemblyName System.Web
Add-Type -AssemblyName System.Web.Extensions

$urlArray = Import-Csv -Path "Scripts\test.csv" | Select -ExpandProperty urls

function Get-WebStatus {

    param( 
        $urlArray 
    )

    foreach ($url in $urlArray) {

        try {
            $request     = Invoke-WebRequest -Uri $url -Method GET
            $statusCode  = $request.StatusCode
        }
        catch {
            $statusCode  = $_.Exception.Response.StatusCode.value__
        }

        "$statusCode returned from $url"

    }
}

Get-WebStatus -urlArray $urlArray

答案 1 :(得分:1)

这是我使用的功能

function Get-UrlResponse ([string] $Url)
{
    try
    {
        $TotalMilliseconds = $(Measure-Command {
            $reply = Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive -Method Head
            $statuscode = $reply.StatusCode
        }).TotalMilliseconds
    }
    catch [Net.WebException]
    {
        $statuscode = [int]$_.Exception.Response.StatusCode
    }

    [pscustomobject]@{
        URL = $url
        StatusCode = $statuscode
        TotalMilliseconds = $TotalMilliseconds
        Date = Get-Date -f yyyyMMdd-HHmmss
    }
}

$urlArray = Import-Csv -Path "Scripts\test.csv" | Select -ExpandProperty urls

foreach ($url in $urlArray) {
    Get-UrlResponse $url
}