Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell Ping代码回复另一种颜色_Powershell_Ping - Fatal编程技术网

Powershell Ping代码回复另一种颜色

Powershell Ping代码回复另一种颜色,powershell,ping,Powershell,Ping,我对编码非常陌生,所以我知道的很少 我正在写我的第一个代码,这是一个ping。它可以ping任何您输入的工作站ID。我希望当它ping时,回复将是绿色的,请求超时将是红色的 我只是想测试一下,从中学习。到目前为止,我有: $Search = Read-Host "Enter Workstation ID" $Reply = ping -t $Search if ($Reply -like "Request Timed Out.") { Write-Host $Reply -Foregr

我对编码非常陌生,所以我知道的很少

我正在写我的第一个代码,这是一个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+Break中断

这就是为什么它看起来“什么也不做”

我可能会选择
testconnection
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时间):


如果您真心希望使用
-t
开关,则不能依赖变量赋值,因为PowerShell将等待
ping.exe
返回(这是有意的,永远不会发生)

但是,您可以通过管道将标准输出从
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
    }
}

什么东西不管用?有错误吗?如果是,它们是什么?它给出了错误的结果吗?没有结果?正确的结果错误的颜色?您可以使用本机PowerShell cmdlet而不是
ping
(>
testconnection
),这将为您节省一些麻烦(字符串解析)。它不会给我一个错误nothing@NickLevesque哦,是的,只是从来没有stops@sodawillowIs
测试连接-计数([int]::MaxValue)
足够近吗?:)我遇到过
-计数小于
2
的故障,计算机只能从收到的第二个数据包或其他数据包进行应答。是的,我肯定需要-t,因为如果用户在网络上遇到问题或现场服务器本身正在丢弃数据包,我将使用它来观察丢弃的数据包。@NickLevesque啊,我明白了,这也有一个解决方案!)我
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
    }
}