powershell max ping ip

<pre class="wp-block-syntaxhighlighter-code">################################################################################
# --- Paramètres ---
$cfgPath          = "C:\logs\ns.conf"
$outCandidates    = "C:\logs\ns_candidates_ips.txt"
$outPingCsv       = "C:\logs\ns_ping_results.csv"
$outContextReport = "C:\logs\ns_ip_context_report.txt"

# Bonus: contexte autour des occurrences
$contextLines     = 2
$contextOnlyForNonPing = $true   # $false = contexte complet pour toutes les IP candidates

# Colonne CSV "Context" (résumé court)
$contextSummaryMaxLines = 3

# --- Ping rapide compatible Windows PowerShell 5.1 (Win10) ---
function Test-PingFast {
  param(
    [Parameter(Mandatory=$true)][string]$Ip,
    [int]$TimeoutMs = 1000
  )
  try {
    $p = New-Object System.Net.NetworkInformation.Ping
    $r = $p.Send($Ip, $TimeoutMs)
    return ($r.Status -eq [System.Net.NetworkInformation.IPStatus]::Success)
  } catch {
    return $false
  }
}

# --- Regex IPv4 robuste ---
$ipv4Regex = '(?<!\d)(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?!\d)'

function Get-IpContextSummary {
  param(
    [Parameter(Mandatory=$true)][string]$Ip,
    [Parameter(Mandatory=$true)][string[]]$Lines,
    [int]$MaxLines = 3
  )

  $pat = '(?<!\d)' + [regex]::Escape($Ip) + '(?!\d)'
  $snips = New-Object System.Collections.Generic.List[string]

  for($i=0; $i -lt $Lines.Length; $i++){
    if([regex]::IsMatch($Lines[$i], $pat)){
      $lineText = ($Lines[$i] -replace '\s+', ' ').Trim()
      if($lineText.Length -gt 200){ $lineText = $lineText.Substring(0,200) + '...' }
      $snips.Add(("L{0}: {1}" -f ($i+1), $lineText)) | Out-Null
      if($snips.Count -ge $MaxLines){ break }
    }
  }

  if($snips.Count -eq 0){ return "" }
  return ($snips -join " || ")
}

# --- Lecture conf ---
$cfgRaw = Get-Content $cfgPath -Raw
$lines  = $cfgRaw -split "`r?`n"

# 1) Toutes les IP trouvées dans la conf
$allIPs = [regex]::Matches($cfgRaw, $ipv4Regex) | ForEach-Object { $_.Value } | Sort-Object -Unique

# 2) IP à exclure : routes
$routeLines = $lines | Where-Object { $_ -match '^\s*add\s+route\b' }
$routeIPs   = foreach($l in $routeLines){ [regex]::Matches($l,$ipv4Regex) | ForEach-Object Value }
$routeIPs   = $routeIPs | Sort-Object -Unique

# 3) IP à exclure : IP locales NetScaler (NSIP/SNIP/VIP/loopback…)
$localLines = $lines | Where-Object {
    $_ -match '^\s*add\s+ns\s+ip\b' -or
    $_ -match '^\s*set\s+ns\s+config\b' -or
    $_ -match '^\s*add\s+ns\s+loopback\b' -or
    $_ -match '^\s*add\s+ns\s+rpcNode\b'
}
$localIPs = foreach($l in $localLines){ [regex]::Matches($l,$ipv4Regex) | ForEach-Object Value }
$localIPs = $localIPs | Sort-Object -Unique

# 4) Exclusions supplémentaires (masques / réservées)
$knownMasks = @(
  '255.255.255.255','255.255.255.0','255.255.254.0','255.255.252.0','255.255.248.0','255.255.240.0',
  '255.255.224.0','255.255.192.0','255.255.128.0','255.255.0.0','255.0.0.0','0.0.0.0'
)

$exclude = ($routeIPs + $localIPs + $knownMasks) | Sort-Object -Unique

# 5) Candidats = toutes les IP - exclusions (et on vire APIPA + loopback)
$candidates = $allIPs |
  Where-Object { $exclude -notcontains $_ } |
  Where-Object { $_ -notmatch '^127\.' } |
  Where-Object { $_ -notmatch '^169\.254\.' } |
  Sort-Object -Unique

# Sauvegarde liste candidats
$candidates | Set-Content -Encoding UTF8 $outCandidates

# 6) Ping rapide + export CSV (+ colonne Context)
$results = foreach($ip in $candidates){
  $ok = Test-PingFast -Ip $ip -TimeoutMs 1000
  $ctx = Get-IpContextSummary -Ip $ip -Lines $lines -MaxLines $contextSummaryMaxLines

  [pscustomobject]@{
    IP      = $ip
    Ping    = $ok
    Context = $ctx
  }
}
$results | Export-Csv -Path $outPingCsv -NoTypeInformation -Delimiter ';' -Encoding UTF8

# 7) BONUS: rapport de contexte complet (où l'IP apparaît + +/- $contextLines lignes)
$targets = if($contextOnlyForNonPing){
  $results | Where-Object { $_.Ping -eq $false } | Select-Object -ExpandProperty IP
} else {
  $candidates
}

"NetScaler ns.conf IP context report" | Set-Content -Encoding UTF8 $outContextReport
"Config: $cfgPath" | Add-Content -Encoding UTF8 $outContextReport
"Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Add-Content -Encoding UTF8 $outContextReport
"" | Add-Content -Encoding UTF8 $outContextReport

$maxIndex = $lines.Length - 1

foreach($ip in $targets){
  $pat = '(?<!\d)' + [regex]::Escape($ip) + '(?!\d)'

  $hitIdx = New-Object System.Collections.Generic.List[int]
  for($i=0; $i -lt $lines.Length; $i++){
    if([regex]::IsMatch($lines[$i], $pat)){
      $hitIdx.Add($i) | Out-Null
    }
  }

  "====================================================================" | Add-Content -Encoding UTF8 $outContextReport
  "IP: $ip | Occurrences: $($hitIdx.Count)" | Add-Content -Encoding UTF8 $outContextReport

  foreach($idx in $hitIdx){
    $start = [Math]::Max(0, $idx - $contextLines)
    $end   = [Math]::Min($maxIndex, $idx + $contextLines)

    "" | Add-Content -Encoding UTF8 $outContextReport
    "---- Occurrence @ line $($idx+1) ----" | Add-Content -Encoding UTF8 $outContextReport

    for($j=$start; $j -le $end; $j++){
      $prefix = if($j -eq $idx) { ">" } else { " " }
      $ln = "{0}{1,6}: {2}" -f $prefix, ($j+1), $lines[$j]
      $ln | Add-Content -Encoding UTF8 $outContextReport
    }
  }

  "" | Add-Content -Encoding UTF8 $outContextReport
}

# --- Résumé ---
"OK : $($candidates.Count) IP candidates"
"Liste candidats : $outCandidates"
"Ping CSV        : $outPingCsv"
"Rapport contexte: $outContextReport"


# 8) Affichage dans la console (tableau) + pagination robuste
$showKoOnly = $true       # <-- mets $false pour tout afficher
$usePaging = $true
$maxContextChars = 180
$pagerWidth = 240

$pingOK = ($results | Where-Object { $_.Ping }).Count
$pingKO = ($results | Where-Object { -not $_.Ping }).Count

Write-Host ""
Write-Host "Résumé: Candidates=$($results.Count) | Ping OK=$pingOK | Ping KO=$pingKO"
Write-Host ""

$displayBase = if($showKoOnly){
  $results | Where-Object { -not $_.Ping }
} else {
  $results
}

$display = $displayBase |
  Sort-Object Ping, IP |
  Select-Object IP, Ping, @{
    Name = 'Context'
    Expression = {
      if([string]::IsNullOrWhiteSpace($_.Context)) { "" }
      elseif($_.Context.Length -gt $maxContextChars) { $_.Context.Substring(0, $maxContextChars) + "..." }
      else { $_.Context }
    }
  }

if($usePaging){
  $display |
    Format-Table -AutoSize -Wrap |
    Out-String -Width $pagerWidth -Stream |
    more.com
} else {
  $display | Format-Table -AutoSize -Wrap
}

# Optionnel: Out-GridView (si dispo) - respecte aussi KO only
if(Get-Command Out-GridView -ErrorAction SilentlyContinue){
  $displayBase | Out-GridView -Title ("NetScaler - Ping Results " + ($(if($showKoOnly){"(KO only)"}else{"(All)"})))
}


</pre>