我可以使用Powershell来检查系统是否重新启动吗?

问题描述 投票:0回答:1

我目前正在修改一些代码,下面是当前未修改的代码。出于隐私原因,实际文件路径替换为“文件路径”。

Clear-Host
       $YN = Read-Host -Prompt "CONFIRM REBOOT [Y/N]"

       if(($YN -eq "Y") -or ($YN -eq "y"))
       {
           Get-ChildItem -Path "File Path" -Recurse -File | Move-Item -Destination "File Path\Archive" -Force

           $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
           $Log = New-Item "File Path\$(Get-Date -f yyyy-MM-dd_hh-mm-ss) Restarts.txt" -ItemType File -Force
           $date = Get-Date -Format "dd-MMM-yyyy hh:mm:ss"

           Clear-Host
           Write-Host `n `n `n
           Write-Host "Rebooting all servers and verifying reboot status..." `n `n
           Write-Host "Please standby, process may take up to 30 minutes..." `n `n

           Restart-Computer -ComputerName $Servers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800

           "----------------------------------Script executed on $date----------------------------------" + "`r`n" | Out-File $Log -Append

           foreach($computer in $Servers)
           {
               $PingRequest = Test-Connection -ComputerName $computer -Count 1 -Quiet
               if($PingRequest -eq $true)
               {
                   Add-Content -Path $Log -Value "$computer`: Reboot Successful." # Issue is here
               }
               else
               {
                   Add-Content -Path $Log -Value "$computer`: Please manually check server."
               }
           }

           Add-Content -Path $Log -Value "`n"
           Clear-Host
           Write-Host `n `n `n
           Write-Host "All done!" `n
           Write-Host "Please review logs, as script may have run into problems." `n `n
           Log-Location
           Pause
       }
       else
       {
           Clear-Host
           Write-Host `n `n `n
           Write-Host "Server Reboots Aborted." `n `n
           Pause
       }

我的问题是目前的脚本,它只是执行一个 ping 请求,仅确认服务器是否已打开,而不是确认服务器是否实际重新启动。有没有办法让 PowerShell 检查服务器是否确实已重新启动,或者这是 PowerShell 可以做的最好的事情吗?

powershell restart
1个回答
0
投票

您可以从

.LastBootUpTime
 查询 
win32_operatingsystem
,然后检查该值是否大于之前存储的日期:

$now = [datetime]::Now
Restart-Computer -ComputerName $Servers -Wait -For PowerShell -Delay 2 -Force -Timeout 1800

foreach ($computer in $Servers) {
    $lastBoot = (Get-CimInstance Win32_OperatingSystem -ComputerName $computer -EA 0).LastBootUpTime
    if ($lastBoot -gt $now) {
        Add-Content -Path $Log -Value "$computer`: Reboot Successful." # Issue is here
    }
    else {
        Add-Content -Path $Log -Value "$computer`: Please manually check server."
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.