Reputation: 45
I'm currently modifying some code, and below is what the current unmodified code is. For privacy reasons, actual file paths are replaced with "File Path".
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
}
My issue is the script as it currently stands, it simply does a ping request, which only confirms if the server is turned ON, not if it actually restarted. Is there a way for me to get PowerShell to check if the server has actually been restarted, or is this the best that PowerShell can do?
Upvotes: 1
Views: 922
Reputation: 60838
You can query the .LastBootUpTime
from win32_operatingsystem
and then check that the value is greater than a previously stored date:
$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."
}
else {
Add-Content -Path $Log -Value "$computer`: Please manually check server."
}
}
Upvotes: 1