Skip to content

Reboot A Remote Machine

Code

<#
.SYNOPSIS
Reboot a specific host machine

.DESCRIPTION
Reboots a specific host machine but also ensures that the machine being rebooted 
is the correct one by directly querying it to confirm DNS resolution.

.NOTES
REVISION ID  : 2
UPDATED      : 2024-09-23
AUTHOR       : Noxcivis
LICENSE      : MIT
SOURCE       : https://noxcivis.supportmarks.com
NOTES        : No additional notes
LOCAL ADMIN  : Not required
REMOTE ADMIN : YES
#>

Clear-Host

# Prompt the user to enter the machine name
$machine = Read-Host "Enter the name of the machine you want to reboot"

# Check if the machine name is blank
if ([string]::IsNullOrWhiteSpace($machine)) {
    Write-Output "No machine name entered. Exiting script."
    exit
}

# Prompt the user for confirmation
$confirmation = Read-Host "Are you sure you want to reboot a machine? (Yes/No)"

if ($confirmation -eq "Yes" -or $confirmation -eq "Y" -or $confirmation -eq "y") {

    # Resolve the DNS name
    $dnsInfo = Resolve-DnsName -Name $machine

    if ($dnsInfo) {
        Write-Output "DNS resolution successful for $machine. Proceeding to confirm hostname."

        # Query the remote machine for its hostname
        $hostname = Invoke-Command -ComputerName $machine -ScriptBlock { hostname }

        if ($hostname -eq $machine) {
            Write-Output "Hostname confirmed for $machine. Proceeding with reboot."
            # Reboot the machine
            try {
                Write-Output "Hostname confirmed for $machine. Proceeding with reboot."
                # Reboot the machine without waiting for completion
                Invoke-Command -ComputerName $machine -ScriptBlock { shutdown /r /t 0 } -AsJob
                Write-Output "Reboot command sent to $machine.  Not waiting."
            }
            catch {
            }
        } else {
            Write-Output "Hostname mismatch for $machine. Expected: $machine, Found: $hostname. Skipping reboot."
        }
    } else {
        Write-Output "DNS resolution failed for $machine. Skipping reboot."
    }
} else {
    Write-Output "Operation cancelled by user."
}

TIP

Save as reboot-a-remote-machine.ps1