Search code examples
powershellpowershell-3.0

Looping through array and returning results of each object in Powershell


I need some help with the following PS code:

$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"}

The actual output of $request returns the headers of all 3 sites, so how do I get the exact site that failed the test?

Thanks in advance


Solution

  • Try something like this:

    "www.site1.com","www.site2.com", "www.site3.com" |
        ForEach-Object {
            $response = Invoke-WebRequest $_ -Method Head
    
            [PsCustomObject]@{
                Site = $_
                StatusCode = $response.StatusCode
            }
        }
    

    You can filter the output by appending the following after the last bracket:

    | Where-Object StatusCode -ne 200