PowerShell - Reboots

Published: 24 August 2021
on channel: Mr Automation
1,012
16

(How to reboot lots of servers at once and keep track of the status)

In this video I demonstrate how you reboot a bunch of servers all at once, and keep track of the failures and successes. restart-computer cmdlet is used in conjunction with start-job to take care of the multithreading.

*reboot with logging
*restart-computer
*restart multiple computers at once
*powershell
*learn powershell
*automation
*learn automation
*windows
*windows powershell
*automatic installations
*configuration as code

Code:

function rebootSystem {
param(
[Parameter(Mandatory)]$Computer,
[Parameter(Mandatory)]$userCreds
)
try {
Restart-Computer -Credential $userCreds -ComputerName $Computer -Wait -Force -ErrorAction Stop
$props = [ordered]@{
name = $Computer
result = "Success"
}
}
catch {
$props = [ordered]@{
name = $Computer
result = "Failed $($_.exception.message)"
}
}

return (new-object psobject -property $props)
}

$CWD = Split-Path -parent $MyInvocation.MyCommand.Definition #Current Dir of script
$Computers = Get-Content "$CWD\servers.txt"
$domainCreds = Get-Credential

foreach ($Computer in $Computers) {
Write-Output "Starting reboot on $Computer"
start-job -ScriptBlock ${function:rebootSystem} -ArgumentList $Computer,$domainCreds | Out-Null
}

while (get-job | where State -eq 'Running'){
$jobcount = (get-job | where State -eq 'Running').count
Write-Output "We are still waiting on $jobcount reboots, sleeping for 10 seconds and check again"
Start-Sleep -Seconds 10
}

$logfile = "$CWD\reboot-$(get-date -Format 'yy-MM-dd-hh-mm-ss').log"
$endresult = get-job | Receive-Job -Force -Wait
get-job | Remove-Job
$endresult | Select name, result | ogv

foreach ($result in $endresult){
"$($result.name), $($result.result)" | Out-File $logfile -Append
}
#we can all sort of things with this output, for example we can filter out the failed ones or just write them all to a log file.


Watch video PowerShell - Reboots online, duration hours minute second in high quality that is uploaded to the channel Mr Automation 24 August 2021. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 1,012 times and liked it 16 visitors.