techthoughts2
2/11/2016 - 5:17 AM

Hyper-V VM AutomaticStopAction

First part of script evaluates all Hyper-V VMs AutomaticStopAction setting to determine how much drive space is being wasted by the default Save setting. Second part of script enables you to mass change the setting to Shutdown on all VMs on the server.

#determine if current VM AutomaticStopAction settings is using up a lot of harddrive space
#---------------------------------------------------------
$vmMemory = 0
#---------------------------------------------------------
try {
    $vms = Get-VM -ErrorAction Stop
    foreach ($vm in $vms) {
        if ($vm.AutomaticStopAction -eq "Save") {
            $vmMemory += [math]::round($vm.MemoryAssigned / 1GB, 0)
        }
    }
    Write-Output "VM .bin files are reserving a total of: $vmMemory GB of Hard Drive Space"
}
catch {
    Write-Output "An error was encountered getting VM information:"
    Write-Error $_
}


#*********************************************************
#the following code will interact with the user to determine if they would like to change
#the AutomaticStopAction for all VMs on the server

#warn user
Write-Output "This will SHUT-DOWN all VMs that are set to AutomaticStopAction 'Save',"`
    "change to 'Shutdown', and the start the VMs back up"
#ask user if they are ABSOLUTELY sure they want to do this
while ("Y", "N", "y", "n" -notcontains $choice) {
    $choice = Read-Host "Are you ABSOLUTELY sure you want to proceed? (Y/N)"
}
if ($choice -eq "Y" -or $choice -eq "y") {
    try {
        $vms = Get-VM -ErrorAction Stop
        Write-Output "----------------------------------"
        foreach ($vm in $vms) {
            if ($vm.AutomaticStopAction -eq "Save") {
                $vmname = $vm.Name
                Write-Output "Stopping $vmname ..."
                Stop-VM -Name $vmname -ErrorAction Stop | Out-Null
                Write-Output "Changing AutomaticStopAction to ShutDown..."
                Set-VM -Name $vmname -AutomaticStopAction ShutDown -ErrorAction Stop
                Write-Output "Starting $vmname ..."
                Start-VM -Name $vmname -ErrorAction Stop
                Write-Output "Started."
                Write-Output "----------------------------------"
            }
        }
    }
    catch {
        Write-Output "An error was encountered:"
        Write-Error $_
    }
}
else {
    Write-Output "No action taken."
}