Check for open application and reboot Hyper-V VM
I’ve recently had a requirement for a scheduled reboot of a large group of Hyper-V VDIs. Due to the nature of the line of business application, it was imperative that we checked that several specific apps were not running before the reboot was ran. Here is an example of the script I wrote for this task. Simply replace the $process, $process2, etc. with your specific application (name only, no path or .exe, etc. requirement). The script checks the running process on the VDI, if one of the apps are running it breaks the loop for that VM and continues to the next, otherwise it reboots the VM and notifies the user. Here’s the script:
$vms2reboot = get-vm | Where-Object Name -like *test-vm001* | Select-Object -Expand Name
$process = “Notepad”
$process2 = “Calc”
$process3 = “Mspaint”
start-transcript “C:\reboot-vms.log”
foreach ($vm2reboot in $vms2reboot){
if(get-process -Computername $vm2reboot | where-object {
$_.ProcessName -contains “$process” -or
$_.ProcessName -contains “$process2”-or
$_.ProcessName -contains “$process3”
})
{
Write-Host “A business app is currently running. Reboot will not continue on $vm2reboot”
}
Else {write-host “Rebooting VM $vm2reboot”
shutdown -r -f -m \\$vm2reboot -c “Reboot commencing for maintenance”
}
}
stop-transcript
If one of the apps are open, reboot does not continue:
Otherwise it reboots the VM: