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

10-04-2015 9-10-51 p-m-new

If one of the apps are open, reboot does not continue:

10-04-2015 9-16-53 p-m-

Otherwise it reboots the VM:

10-04-2015 9-15-12 p-m-

10-04-2015 9-14-37 p-m-

 

About AJ McKean

Based in sunny Tauranga, New Zealand, AJ McKean is a Senior Systems Engineer in Mt Maunganui. With over 15 years of professional IT experience working in both New Zealand and the United States, he holds several certifications including MCSE(2000-2003), MCITP:Enterprise(2008), MCSA(2012), VMware VCP-DCV5.5, CompTIA A+ & is an HP Storage Architect. He is passionate about all things IT, especially virtualization, automation & cloud technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *