如何在循环外获取值-Powershell

时间:2018-10-23 16:23:07

标签: html powershell

您好,我写了一个小函数来检查网站是否可用。我想带出价值-状态之外的价值,并创建一个不错的html输出。我不得不使用循环从$ hash检查每个网站。

Function MyFunction{
clear-host
$hash = @{"ING"= "http://google.pl/" ; "youtube" = "https://youtube.com/" ;}
$weburl = $hash.Values 
foreach ($weburls in $weburl){ 
$HTTP_Request = [System.Net.WebRequest]::Create($weburls)
$HTTP_Response = $HTTP_Request.GetResponse() 
# We then get a response from the site.
$HTTP_Status = [int]$HTTP_Response.StatusCode # We then get the HTTP code as an integer.
If ($HTTP_Status -eq 404 -or $HTTP_Status -eq 503 -or $HTTP_Status -eq 403 ) {
    Write-Host "$weburls The Site may be down, please check. - status is $HTTP_Status!"
    $URLRESP = New-Object -TypeName psobject
    $URLRESP | Add-Member -MemberType NoteProperty -Name  Status -Value "The Site may be down, please check!"
    [array]$URLRES += $URLRESP
}
Else {
    Write-Host "OK"
    $URLRESP = New-Object -TypeName psobject
    $URLRESP | Add-Member -MemberType NoteProperty -Name  Status -Value "OK"
    [array]$URLRES += $URLRESP
}
$HTTP_Response.Close() # Finally, we clean up the http request by closing it.    }

循环到此结束。现在,我将其转换为具有值-名称,值,链接的html,在这里我要添加一个新值-“ 状态”,其结果为“确定”或“无效链接”等。< / p>

    $hash.GetEnumerator() | sort -Property Name | Select-Object Name, Value, Status | 
    ConvertTo-HTML -Head $headLink  -Property *,@{Label="Link";Expression={"
}

$html_url = MyFunction 
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($html_url) | Out-File  "\\......\scresult\test.htm" -Append

我不知道如何将值“ status”放在它的外面。抱歉,我根本不擅长脚本编写,而且我不知道如何执行脚本。我有一种感觉,如果我只是将输出线放入循环内,它将按值相乘。

2 个答案:

答案 0 :(得分:1)

进行一些更改,这是我能够测试的工作脚本。我认为这将帮助您获得所需的东西

[System.Collections.ArrayList]$Results = @()

Function MyFunction {
    Clear-Host
    $hash = @{
        "ING"     = "http://google.com/"
        "youtube" = "https://youtube.com/"
    }    
    $weburl = $hash.Values 
    foreach ($url in $weburl){ 
        $HTTP_Request = [System.Net.WebRequest]::Create($url)
        $HTTP_Response = $HTTP_Request.GetResponse()
        $HTTP_Status = [int]$HTTP_Response.StatusCode

        If (($HTTP_Status -eq 404) -or ($HTTP_Status -eq 503) -or ($HTTP_Status -eq 403)) {
            Write-Host "$url The Site may be down, please check. - status is $HTTP_Status!"            
        }
        Else {
            Write-Host "$url is OK"            
        }
        $HTTP_Response.Close()

        $Result = [PSCustomObject]@{
            URL = $url
            Status = $HTTP_Status
        }
        $Results.Add($Result) | Out-Null
    }
}

MyFunction

$Results

编辑

再次查看后,如果导致不良响应,它将引发异常。您将需要添加一些错误处理,例如try catch,并可能解析该错误以获取确切的错误代码。我进行快速测试时以为它返回错误代码。

  

使用“ 0”参数调用“ GetResponse”的异常:“远程服务器返回错误:(503)服务器不可用。”   在第1行:char:1   + $ HTTP_Request.GetResponse()   + ~~~~~~~~~~~~~~~~~~~~~~~~~~       + CategoryInfo:未指定:(:) [],MethodInvocationException       + FullyQualifiedErrorId:WebException

答案 1 :(得分:1)

您的问题分为2部分。如何获取数据?如何将其传递给ConvertTo-HTML?

您的第一个问题是通过创建一个Arraylist并添加一个带有您要传递的属性的PSCustomObject来解决的。这样,您可以将最终返回的Hashtables数组与相同的Keys关联起来。

function GetSiteStatus(){
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        [hashtable]$WebSiteInfo
    )
    process{
        $Response = New-Object System.Collections.ArrayList
        $WebSiteInfo.GetEnumerator() | %{
            $Item = $_
            try{ 
                $status = Invoke-WebRequest -Uri $_.Value | %{
                    if(@('404','503','403') -match $_.StatusCode){
                        "$($Item.Key) The Site may be down, please check. - status is $($_.StatusCode)"
                    }else{
                        "OK"
                    }
                }
                $Response.Add([PSCustomObject]@{"Name"= $Item.Key; "Value"=$Item.Value; "Status"=$Status; "Link"=$($Item.value)}) | out-null
            }catch{
                $Status = "$($Item.Key), $_."
                $Response.Add([PSCustomObject]@{"Name"= $Item.Key; "Value"=$Item.Value; "Status"=$Status; "Link"=$($Item.value)}) | out-null
            }
        }
        return $Response
    }
}

关于第二个问题,这是如何使用该函数并将返回值传递到convertto-htmlout-file.

$HTML = @{
    "Test403" = "https://httpstat.us/403"; 
    "Test404" = "https://httpstat.us/404";
    "Test503" = "https://httpstat.us/503";
    "Google" = "http://www.Google.com";
    "GoogleFake" = "https://GoogleFAKE1312.com"
} | GetSiteStatus | ConvertTo-Html -Property Name,Value,Status,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}

Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($HTML) | Out-File C:\TEST\test.htm