循环遍历数组并返回Powershell中每个对象的结果

时间:2018-05-23 10:17:37

标签: powershell powershell-v3.0

我需要以下PS代码的帮助:

$site1 = "www.site1.com"
$site2 = "www.site2.com"
$site3 = "www.site3.com"
$sites = $site1,$site2,$site3
$request = foreach ($site in $sites) {invoke-webrequest $site -method head}
if ($request.StatusCode -ne "200"){write-host "site is not working"}

$ request的实际输出返回所有3个站点的标题,那么如何获得未通过测试的确切站点?

提前致谢

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

"www.site1.com","www.site2.com", "www.site3.com" |
    ForEach-Object {
        $response = Invoke-WebRequest $_ -Method Head

        [PsCustomObject]@{
            Site = $_
            StatusCode = $response.StatusCode
        }
    }

您可以通过在最后一个括号后附加以下内容来过滤输出:

| Where-Object StatusCode -ne 200