简体   繁体   English

Powershell,ping 结果为彩色

[英]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.一直在为我的工作在 PowerShell 中编写脚本/模块,并且似乎无法找到输入的位置/内容以使 ping 结果如果成功则变为绿色,如果超时则变为红色。

  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返回一个字符串数组,因此您可以检查Foreach返回的行:

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.您可能需要本地化 if。 Eg in a german environment Request timed out is Zeitberschreitung der Anforderung.例如,在德国环境中, Request timed outZeitberschreitung der Anforderung.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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