Skip to content

Instantly share code, notes, and snippets.

@jeremy-jameson
Last active December 10, 2019 16:42
Show Gist options
  • Save jeremy-jameson/37c4904d9d7d7be3ba4d5ab680ceda59 to your computer and use it in GitHub Desktop.
Save jeremy-jameson/37c4904d9d7d7be3ba4d5ab680ceda59 to your computer and use it in GitHub Desktop.
Start and stop cluster VMs (using System Center Virtual Machine Manager)

# Start and stop cluster VMs (using System Center Virtual Machine Manager)

# Create cluster VM list with "startup order"

$url = 'https://gist.githubusercontent.com/jeremy-jameson' `
    + '/913c11a4550efe428bbe7d6e1c82c955/raw'

Invoke-WebRequest `
    -UseBasicParsing `
    -Uri $url `
    -OutFile 'C:\NotBackedUp\Temp\Cluster VMs.csv'

Note:

The previous PowerShell command downloads a sample list of virtual machines running on a cluster with "startup order" to a file. You will need to modify the list accordingly for your environment.

# Start VMs in desired order

Import-Csv 'C:\NotBackedUp\Temp\Cluster VMs.csv' |
    sort @{ e = {$_.StartupOrder -as [int]} } |
    where { $_.StartupOrder -ne 0 } |
    foreach {
        $vm = Get-SCVirtualMachine -Name $_.Name

        If ($vm)
        {
            If ($vm.VirtualMachineState -ne 'Running')
            {
                Write-Verbose "Starting VM ($($vm.Name))..."

                Start-SCVirtualMachine $vm |
                    select Name, MostRecentTask, MostRecentTaskUIState

                Start-Sleep -Seconds 30
            }
        }
    }

# Stop VMs in desired order

Import-Csv 'C:\NotBackedUp\Temp\Cluster VMs.csv' |
    sort @{ e = {$_.StartupOrder -as [int]} } -Descending |
    foreach {
        $vm = Get-SCVirtualMachine -Name $_.Name

        If ($vm)
        {
            If ($vm.VirtualMachineState -eq 'Running')
            {
                Write-Verbose "Stopping VM ($($vm.Name))..."

                Stop-SCVirtualMachine $vm |
                    select Name, MostRecentTask, MostRecentTaskUIState
            }
        }
    }

# Stop highly available VMs (in desired order)

Import-Csv 'C:\NotBackedUp\Temp\Cluster VMs.csv' |
    sort @{ e = {$_.StartupOrder -as [int]} } -Descending |
    foreach {
        $vm = Get-SCVirtualMachine -Name $_.Name |
            where { $_.IsHighlyAvailable -eq $true }

        If ($vm)
        {
            If ($vm.VirtualMachineState -eq 'Running')
            {
                Write-Verbose "Stopping VM ($($vm.Name))..."

                Stop-SCVirtualMachine $vm |
                    select Name, MostRecentTask, MostRecentTaskUIState
            }
        }
    }

Note:

This is used when it is necessary to take the cluster shared volumes offline -- e.g. to upgrade the NAS (Network Attached Storage).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment