Actions

Powershell: Ping Stuff

From Rabbi Blog

Revision as of 19:54, 6 August 2026 by Rabbi Bob (talk | contribs) (Created page with "Category:Powershell Category:Weblog-2026-08 Provide a list of IP addresses, run the script. Checks DNS and outputs a results file. =Code= <pre> $deviceNames = Get-Content "devices.txt" $results = @() foreach ($name in $deviceNames) { $status = "Unknown" try { # Attempt to resolve DNS [System.Net.Dns]::GetHostEntry($name) $status = "Resolving..." # Check if device pings (up to 4 attempts with 1 second timeout) if (Test-Connect...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


Provide a list of IP addresses, run the script. Checks DNS and outputs a results file.


Code

$deviceNames = Get-Content "devices.txt"

$results = @()

foreach ($name in $deviceNames) {
  $status = "Unknown"
  
  try {
    # Attempt to resolve DNS
    [System.Net.Dns]::GetHostEntry($name)
    $status = "Resolving..."
    
    # Check if device pings (up to 4 attempts with 1 second timeout)
    if (Test-Connection -ComputerName $name -Count 1 -Quiet) {
      $status = "Up"
    } else {
      $status = "Down"
    }
  } catch {
    # Handle DNS resolution failure
    $status = "NO DNS"
  }

  # Create a custom object for each device
  $result = New-Object PSObject -Property @{
    Name = $name
    Status = $status
  }
  
  # Add object to results array
  $results += $result
}

# Export results to CSV
$results | Export-Csv -Path "results.csv" -NoTypeInformation -Force

Write-Host "Results exported to 'results.csv'"