[英]Test-Connection powershell
我是 PS 的初学者,但我试图让我的生活更轻松,创建一个重新启动计算机的按钮,然后告诉我它何时在线。 我一直在尝试 -Wait 参数,但会抛出错误。 如果有人能指出我正确的方向,那就太好了。
Restart_Computer_Click ={
$again = 1
While($again -ne 'N'){
$ComputerName = Read-Host "ComputerName"
#output online
if (Test-connection $ComputerName -quiet -count 2){
write-host -foregroundcolor green "$ComputerName is online"
Restart-computer -computername $ComputerName -Force -Confirm
}
else{
#output -offline
write-host -foregroundcolor red "$ComputerName is offline"
}
$again = read-host "Reboot Again? y/n"
$again.toUpper() | out-null
}
}
真幸运——我实际上已经在这个问题上花费了大量时间,因为我每个月都必须重新启动数百台服务器以应用更新。 我了解您希望 -wait 命令能做什么,恐怕我知道它为什么不起作用。 restart-computer 命令只是向计算机发送重新启动信号。 powershell 中没有内置逻辑来说“重新启动计算机并等待它重新联机”,因此等待命令将无济于事。
相反,您的脚本需要几个额外的步骤:
请参阅下面的修改后的代码。 我尝试添加大量评论,以便您可以看到我在添加步骤时的逻辑。 我不得不将我的脚本从针对多台计算机运行调整为单台计算机,但这应该可以解决问题。 我的一个假设是您已经弄清楚了脚本的按钮单击部分,只需要帮助等待重新启动。
Restart_Computer_Click =
{
$computer = "localhost"
$again = 1
While ($again -ne 'N')
{
$ComputerName = Read-Host "ComputerName"
#output online
if (Test-connection $ComputerName -quiet -count 2)
{
write-host -foregroundcolor green "$ComputerName is online"
Restart-computer -computername $ComputerName -Force -Confirm
$online = $true
}
else
{
#output -offline
write-host -foregroundcolor red "$ComputerName is offline"
$online = $false
}
# There's no point in checking the reboot sequence if the computer is offline, so
# let's ignore the process if its offline
if ($online -eq $true)
{
# here's the while loop that will keep checking for the status of the rebooted computer
while ($reboot_complete -ne $true)
{
# First, let's sleep for two minutes to give the system time to reboot
# My systems generally have to install updates, so I have to grant a
# generous reboot time
start-sleep -Seconds 120
# If the computer is in the middle of restarting, we can't check the boot status, so we
# need to wait a little longer
if (Test-Connection $computer -quiet -count 1)
{
$lastboot = Get-WMIObject Win32_OperatingSystem -ComputerName $computer -EA SilentlyContinue
$lastbootdate = $lastboot.converttodatetime($lastboot.LastBootUpTime)
$time_elapsed = (get-date) - $lastbootdate
# This is the main statement that's going to tell us if the system has rebooted
# The time elapsed is the time difference between right now and the time the computer
# was last rebooted. The time elapsed is basically the difference in time. If there's
# less than 10 minutes of difference, I assume its rebooted from the script. If its
# older than that, I assume it hasn't rebooted yet. For example, you can pull a system's
# time while its applying updates as part of the reboot process.
if ($time_elapsed.TotalMinutes -lt 10)
{
$reboot_complete = $true
}
}
}
}
$again = read-host "Reboot Again? y/n"
$again.toUpper() | out-null
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.