Ping码回复另一种颜色
Ping Code to reply another color
我对编码很陌生,所以我知道的很少。
我正在编写我的第一个代码,它是一个 ping。它可以 ping 通您放入其中的任何工作站 ID。我希望当它 ping 时,回复是绿色的,请求超时是红色的。
我只是想测试一下并从中学习。到目前为止我有这个:
$Search = Read-Host "Enter Workstation ID"
$Reply = ping -t $Search
if ($Reply -like "Request Timed Out.") {
Write-Host $Reply -ForegroundColor Red
}
但这不起作用。
如果您查看来自 ping.exe
的用法消息,您会看到 -t
开关使 ping.exe
继续 ping 主机,直到被 Ctrl+C 或 Ctrl+ 中断休息。
这就是为什么它看起来像 "doing nothing"。
我可能会选择 Test-Connection
cmdlet,而不是 ping.exe
:
$Hostname = Read-Host "please enter the hostname..."
if(Test-Connection -ComputerName $Hostname -Quiet)
{
Write-Host "Ping succeeded!" -ForegroundColor Green
}
else
{
Write-Host "Ping failed!" -ForegroundColor Red
}
它没有 -t
参数,但您可以为 -Count
参数提供高得离谱的值,并以此为代价(每个请求之间间隔一秒钟,[int]::MaxValue
给你 2^31 秒,或 68 年的 ping 值):
Test-Connection $Hostname -Count ([int]::MaxValue)
如果你真的想要 -t
开关,你不能依赖对变量的赋值,因为 PowerShell 会等待 ping.exe
到 return(故意,从不发生)。
您 可以 但是通过管道从 ping.exe
输出标准输出,PowerShell 的异步运行时将让它们持续运行,只要您愿意:
function Keep-Pinging
{
param([string]$Hostname)
ping.exe -t $Hostname |ForEach-Object {
$Color = if($_ -like "Request timed out*") {
"Red"
} elseif($_ -like "Reply from*") {
"Green"
} else {
"Gray"
}
Write-Host $_ -ForegroundColor $Color
}
}
我对编码很陌生,所以我知道的很少。
我正在编写我的第一个代码,它是一个 ping。它可以 ping 通您放入其中的任何工作站 ID。我希望当它 ping 时,回复是绿色的,请求超时是红色的。
我只是想测试一下并从中学习。到目前为止我有这个:
$Search = Read-Host "Enter Workstation ID"
$Reply = ping -t $Search
if ($Reply -like "Request Timed Out.") {
Write-Host $Reply -ForegroundColor Red
}
但这不起作用。
如果您查看来自 ping.exe
的用法消息,您会看到 -t
开关使 ping.exe
继续 ping 主机,直到被 Ctrl+C 或 Ctrl+ 中断休息。
这就是为什么它看起来像 "doing nothing"。
我可能会选择 Test-Connection
cmdlet,而不是 ping.exe
:
$Hostname = Read-Host "please enter the hostname..."
if(Test-Connection -ComputerName $Hostname -Quiet)
{
Write-Host "Ping succeeded!" -ForegroundColor Green
}
else
{
Write-Host "Ping failed!" -ForegroundColor Red
}
它没有 -t
参数,但您可以为 -Count
参数提供高得离谱的值,并以此为代价(每个请求之间间隔一秒钟,[int]::MaxValue
给你 2^31 秒,或 68 年的 ping 值):
Test-Connection $Hostname -Count ([int]::MaxValue)
如果你真的想要 -t
开关,你不能依赖对变量的赋值,因为 PowerShell 会等待 ping.exe
到 return(故意,从不发生)。
您 可以 但是通过管道从 ping.exe
输出标准输出,PowerShell 的异步运行时将让它们持续运行,只要您愿意:
function Keep-Pinging
{
param([string]$Hostname)
ping.exe -t $Hostname |ForEach-Object {
$Color = if($_ -like "Request timed out*") {
"Red"
} elseif($_ -like "Reply from*") {
"Green"
} else {
"Gray"
}
Write-Host $_ -ForegroundColor $Color
}
}