← script library

Automated Virtual Machine Restart with PowerShell and Hyper-V

Hyper-VJanuary 10, 2025

In this post, we will introduce a handy PowerShell script designed to automate the restarting of Hyper-V virtual machines. This script allows administrators to efficiently manage VM availability and ensure that services are back online quickly after maintenance or unexpected shutdowns.

powershell
$vmName = "YourVMName" # Replace with the name of your Virtual Machine

$vm = Get-VM -Name $vmName -ErrorAction SilentlyContinue
if (-not $vm) {
    Write-Host "The virtual machine '$vmName' does not exist."
    return
} elseif ($vm.State -eq 'Running') {
    Write-Host "The virtual machine '$vmName' is currently running."
} else {
    Write-Host "The virtual machine '$vmName' is not running. Attempting to start it..."
}

try {
    Start-VM -Name $vmName
    Write-Host "The virtual machine '$vmName' has been started successfully."
} catch {
    Write-Host "ERROR: ""$($_.Exception.Message)"""
}

$vm.Refresh() # Refresh the VM object to get the latest state
Write-Host "Current state of '$vmName': $($vm.State)"

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.