Search code examples
powershelladministrator

powershell: if loop, while the first position of arraylist in in process


I have an arraylist, in which I am going to save some values. I am doing a foreach loop and if a value is going to be saved at the first position of the ArrayList, I want to output a "First position" line and otherwise, nothing should be done. The if block that I wrote below, doesn't work.

<# Don't consider this code from here

[System.Collections.ArrayList]$alist = @()
$al ="keeranpc01,www.google.ch,192.168.0.25"

$al = $al.Split(",")
foreach($h in $al){
    # Abstand vor dem Hostnamen löschen
    if($h.contains(' ')) {
        $h = $h -replace '\s', ''
    }
    $alist.Add($h)
}
to here
#>


#### Start here
[System.Collections.ArrayList]$rear = @()

foreach($ha in $alist) {
    $PingConnetion = Test-Connection $ha -Count 1 -ErrorAction SilentlyContinue
    $pcre = $ha
    $pire =  if($PingConnetion.ResponseTime -ne $null) {Write-output 'Erreichbar'}else{Write-Output 'Nicht Erreichbar'}
    $zure = $PingConnetion.ResponseTime 
    $zeit = Get-Date -Format HH:mm:ss

    if($alist[$_] -eq $alist[0]) {Write-Host 'First position'}
    [void]$rear.Add([PSCustomObject]@{Zeit = $zeit; Host = $pcre; IPv4 = $PingConnetion.IPV4Address.IPAddressToString; Ping = $pire; Zugriffszeit = $zure; })
}

how should I write the if statement so that it is possible? I expect if-statement to work, Only when the first position of ArrayList is in process

thx


Solution

  • What you are tying to do does work except you are tying to compare element zero of your alist to a ordinal position of your alist which is invalid. You would need to compare the following:

    if($ha -eq $alist[0]) {Write-Host 'First position'}
    

    Below is a worked example that might be clearer.

    $input = 1..10    
    foreach($x in $input){
        if($input[0] -eq $x){
            write-host "First Position"
        }
        $x
    }