我有一个ping IP地址并将该信息发送到控制台窗口的脚本。在高ping时间或错过ping的情况下,它也会写入日志。我想在控制台窗口中只保持高ping时间和错过ping,并允许好ping相互覆盖。这可能吗?
对于高ping时间,这是输出(类似的代码用于错过ping)。
$out = ("{0}ms at $(get-date -format G)" -f $ping.ResponseTime)
write-host $out -foregroundcolor "yellow"
$out >> .\runningPing$ipAddress.txt
对于正常的ping时间,输出就是这个。
$out ("{0}ms" -f $ping.ResponseTime)
write-host $out -foregroundcolor "green"
我想让最后一行只是为了正常的ping而覆盖自己,但是当程序运行时,让高位和错过的ping按下屏幕。这是我能用PS做的事吗?
解 感谢@Mathias R. Jensen,我提出了这个解决方案:
if ($ping.statuscode -eq 0) {
if ($ping.responsetime -gt $waitTime) {
$highPings = $highPings + 1
$out = ("{0}ms at $(get-date -format G)" -f $ping.ResponseTime)
[console]::SetCursorPosition(0,$highPings + $droppedPings + 1)
write-host $out -foregroundcolor "yellow"
$out >> $outFile
}
else {
$out = ("{0}ms $i of $pingCount" -f $ping.ResponseTime)
[console]::SetCursorPosition(0,$highPings + $droppedPings + 2)
write-host $out -foregroundcolor "green"
}
}
else {
$droppedPings = $droppedPings + 1
$out = ("missed ping at $(get-date -format G)")
[console]::SetCursorPosition(0,$highPings + $droppedPings + 1)
write-host $out -foregroundcolor "red"
$out >> $outFile
}
答案 0 :(得分:4)
我认为你应该使用Write-Progress
来获得良好的声音。您不需要提供百分比,您可以使用-Status
参数来显示最后一个好的。
这里是我写的一个小例子,它可能会展示它的外观/操作方式(你可以自己执行此操作来查看,它不会解决它只是模拟的任何事情):
$goods = 0
0..100 | % {
if ((Get-Random -Minimum 0 -Maximum 100) -ge 50) {
$goods += 1
Write-Progress -Activity Test -Status "Last good ping: $_ ($goods total good pings)"
} else {
Write-Warning "Bad ping"
}
Start-Sleep -Seconds 1
}
在这种情况下,您甚至可以计算,例如一定比例的好ping并在Write-Progress
中使用,但我想表明您不需要将其用作进度条有用。
答案 1 :(得分:2)
briantist有更好的方法来解决这个问题,但我一直在玩,并且也提出了这个问题。它在ISE中不起作用,但应该在PowerShell控制台上完成它的工作。它使用"`b"
这是退格符,因此文本将在控制台主机写入时覆盖自身。可能没有帮助你,但可能对其他人有用。
switch($ping.ResponseTime){
{$_ -ge 0 -and $_ -le 100}{
$out = "{0}ms" -f $_
$options = @{ForegroundColor = "Green"; NoNewline = $true}
$backup = "`b" * $out.Length
}
{$_ -ge 500 -and $_ -le 900}{
$out = "{0}ms at $(get-date -format G)" -f $_
$options = @{ForegroundColor = "Yellow"; NoNewline = $false}
$backup = "`n"
}
}
Write-Host "$backup$out" @options
使用switch
根据ping时间范围设置选项。设置一个散列到write-host
的小哈希表。不完美,但它显示了另一种方法。
这主要是为了好玩。
答案 2 :(得分:2)
正如我在评论中提到的,光标位置可以通过以下方法控制:
[control]::SetCursorPosition([int]$x,[int]$y)
[console]
类型加速器指向相同的Console
类,使您能够{C}控制台应用程序中的WriteLine()
到控制台。如果您愿意,还可以控制颜色和其他控制台行为:
Clear-Host
[console]::ForegroundColor = "Red"
1..10|%{
[console]::SetCursorPosition(2+$_,$_-1)
[console]::WriteLine("Hello World!")
}
[console]::ForegroundColor = "Green"