0

I'm putting together a reboot script used for scheduling server reboots.

My goal is to improve functionality and error handling by using a loop with counter to break/exit the script if the server:

1) Does not restart. For example While (Test-path "\\$server\c$")

2) Does not come online. For example While (-not(Test-path "\\$server\c$"))

In addition, I'm trying to add logging to a CSV file if any of the above conditions are TRUE. Otherwise the script continues and creates the CSV with the previous reboot time stamp along with current reboot time stamp.

My current attempt does not seem to correctly exit the script and log the failure and honestly I'm a little unsure of how to test this before rebooting servers.

Param([Parameter(Mandatory=$true)][string]$server)
$ErrorActionPreference = "SilentlyContinue"

Try{
$LastReboot = Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select -ExpandProperty TimeGenerated | select -first 1

(Invoke-WmiMethod -ComputerName $server -Path "Win32_Service.Name='HealthService'" -Name PauseService).ReturnValue | Out-Null

Restart-Computer -ComputerName $server -Force

#New loop with counter, exit script if server did not reboot.
$max = 20;$i = 0
DO{
    IF($i -gt $max){

        $hash = @{
             "Server" =  $server
             "Status" = "FailedToReboot!"
             "LastRebootTime" = $LastReboot
          }
    $newRow = New-Object PsObject -Property $hash
    Export-Csv c:\Scripts\RebootCheck.csv -InputObject $newrow -Append -Force
    ;exit}#exit script and log failed to reboot.
    $i++
"Wait for server to reboot"
    Start-Sleep -Seconds 30
}#end DO
While (Test-path "\\$server\c$")

$max = 15;$i = 0
 DO{
    IF($i -gt $max){

        $hash = @{
             "Server" =  $server
             "Status" = "FailedToComeOnline!"
             "LastRebootTime" = $LastReboot
          }
    $newRow = New-Object PsObject -Property $hash
    Export-Csv c:\Scripts\RebootCheck.csv -InputObject $newrow -Append -Force
    ;exit}#exit script and log failed to reboot.
    $i++
    "Wait for [$server] to come online"
    Start-Sleep -Seconds 30
}#end DO
While (-not(Test-path "\\$server\c$"))

$CurrentReboot = Get-EventLog -ComputerName $server -LogName system | Where-Object {$_.EventID -eq '6005'} | Select -ExpandProperty TimeGenerated | select -first 1
        $hash = @{
                 "Server" =  $server
                 "Status" = "RebootSuccessful"
                 "LastRebootTime" = $LastReboot
                 "CurrentRebootTime" = $CurrentReboot
                  }

$newRow = New-Object PsObject -Property $hash
Export-Csv c:\Scripts\RebootCheck.csv -InputObject $newrow -Append -Force

}#End Try.

Catch{
$errMsg = $_.Exception
"Failed with $errMsg"
 }

2 Answers 2

2

In order to break out of a loop, use the break keyword, not return.

Assign $true to $test inside the if block immediately before break:

$test = false
while ($limit -lt $max){
    Write-Host "Reboot Request Sent, waiting for server to reboot"
    if(Test-Path \\Server1\C$){
        Write-Host "Reboot Successful, continue script"
        $test = $true
        break
    }
    $limit++    
    Start-Sleep -Seconds 10    
}

The switch statement you've shown is syntactically valid, but kinda weird, since it's the exact equivalent of a standard if/else:

if($test)
{
    Write-Host "Reboot succeeded!"
}
else
{
    Write-Host "Reboot failed!"
}
Sign up to request clarification or add additional context in comments.

7 Comments

Apologies, I was borrowing example code from @mjolinor Timed loop I'm testing this still and can't get the expected behavior.
Would love to help you, but you're gonna need to explain exactly what you expect and how the codes behavior deviates from your expectations :)
@user4317867 also... have you considered using Restart-Computer Server1 -Wait -Timeout 50 or Restart-Computer Server1 -AsJob |Wait-Job?
In Summary, Restart-Computer is sent. A loop with counter is run next waiting for server's C$ share to go offline to allow the script to continue, next statement is a loop waiting for server's C$ to come online. If the first loop's counter is maxed out, break script. RE: -asjob because I want to write status to a logfile and wasn't sure how to wrap all that up.
@user4317867 I know, we all have to start somewhere, but I'd also really encourage you to step back and re-visit your original question/problem. It seems to me that you're trapping yourself in a common pitfall :)
|
0

After trial and error I believe I have something working.

This example will exit the script after two seconds

#restart-computer $server
$max = 2;$i = 0
 DO{
IF($i -gt $max){"Server failed to reboot!";exit}#exit script and log failed to reboot.
    $i++
"Wait for server to reboot"
    Start-Sleep -Seconds 1
}#end DO
While (Test-path "\\$server\c$")
"Server rebooted, continue script"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.