powershellrestart

restart-computer with logs or result


I need to restart 5 or 6 computers at the same time. It works nice with the command restart-computer. But I want to add -wait to be sure each server has restarted.

So, of course, I can do something like this:

foreach ($VMs in $Servers){
    restart-computer $Servers -force -wait
    Write-Output "$vms has been rebooted"
}

I tried with -asjob, but I don't really understand how it works and how I can have a result. Also, it means I can't use -wait anymore.

Is there a way to export the result of restart-computer to a log or an array?
How can I know if one of the server could not restart, and will the script will continue to run if it's the case?


Solution

  • Restart-Computer gives no output of its own.
    That said, you can simply do something like

    # Creates string list to collect the logs
    $RestartLog = [System.Collections.Generic.List[object]]@()
    
    foreach ($VM in $VMList) {
        # restarts $VM, by force, waits for Powershell to be available, checks every 2 seconds for a total of 300 seconds(5minutes) 
        # if you do not set -Timeout, it will wait forever
        # if the computer doesn't answer before the Timeout is reached, the command goes on.
        Restart-Computer $VM -Force -Wait -For PowerShell -Timeout 300 -Delay 2 -WhatIf
    
        # Prepares Log line
        $RestartLine = 'Computer {0} has been restarted at {1}' -f $VM, (Get-Date)
    
        # add string to list
        $RestartLog.Add($RestartLine)
    
        # optional: write it to the screen
        Write-Host $RestartLine
    }
    
    # append list to log file
    $RestartLog | Out-File -FilePath $FileLog -Append