Reboot a Remote Windows Computer and Wait Until It is Back Online to Continue PowerShell Script

This script will reboot the specified remote computer, wait for it to go offline, and then wait for it to come back online before moving on with the rest of the script.


# Set the target computer name and credentials
$ComputerName = "TargetComputerName"
$Username = "YourUserName"
$Password = "YourPassword"

# Convert the plain text password to a secure string
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force

# Create a PSCredential object
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword

# Function to test the target computer's availability
function Test-ComputerAvailability {
    param($ComputerName)

    try {
        $PingResult = Test-Connection -ComputerName $ComputerName -Count 1 -ErrorAction Stop -Quiet
    } catch {
        $PingResult = $false
    }

    return $PingResult
}

# Reboot the target computer
Restart-Computer -ComputerName $ComputerName -Credential $Credential -Force

# Wait for the computer to go offline
while (Test-ComputerAvailability -ComputerName $ComputerName) {
    Write-Host "Waiting for $ComputerName to go offline..."
    Start-Sleep -Seconds 5
}

# Wait for the computer to come back online
while (-not (Test-ComputerAvailability -ComputerName $ComputerName)) {
    Write-Host "Waiting for $ComputerName to come back online..."
    Start-Sleep -Seconds 5
}

# Continue with the script
Write-Host "$ComputerName is back online. Continuing with the script..."

Comments

Popular posts from this blog

Unveiling the Power of PowerShell Regions: A Comprehensive Guide

PowerShell Script to Remotely Update Firmware on Brother Printers Microsoft

PowerShell to Download All Critical/High Lacework Alerts From the Last 24 Hours