简体   繁体   中英

Powershell, ping results in color

been working on a script/module in PowerShell for my work and can't seem to find where/what to input to make the ping results på green if it's a success and red if they timed out.

  Param (
    [Parameter(Position=0,Mandatory=$true)]
    [String]$StoreID
  )

  $StoreNetworkArray = @(
    ("1017","xxx.x.x.x","x.x.x.x"),

  )

  $checkPing = $False
  foreach ($currentStore in $StoreNetworkArray) {

    if($currentStore[0] -eq $StoreID) {
      $checkPing = $True # StoreID matches!
      $WanIP = $currentStore[1]
      $BreakoutIP = $currentStore[2]
    } # end if
  } # end foreach

  if ($checkPing) {
    # Store found, lets ping!
    Write-Host "Checking status for store $StoreID using ping"
    Write-Host "-----------------------------------------"
    Write-Host "Pinging WAN IP: $WanIP"
    ping $WanIP /n 10 
    Write-Host "-----------------------------------------"
    Write-Host "Pinging Breakout IP: $BreakoutIP"
    ping $BreakoutIP /n 10
    Write-Host "-----------------------------------------"
  }
} # End Function Check-StorePing```

ping returns an array of strings so you can check Foreach returned line:

ping $WanIP /n 10 | foreach {
    if ($_ -like '*TTL=*'){
        Write-Host $_ -ForegroundColor Green
    }elseif($_ -like '*timed out*'){           # you might need to localize this part
        Write-Host $_ -ForegroundColor Red
    }else{                                     # remove the last else to get rid of the extra lines before and after the ping
        Write-Host $_
    }
} 

You can even fit all of this in a single line but for now this has a better overview. You might need to localize the if. Eg in a german environment Request timed out is Zeitberschreitung der Anforderung.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM