• Skip to primary navigation
  • Skip to main content

jdgreen.io

The personal blog of James Green

  • Home
  • Technology
    • Announcements
    • Industry
    • Reviews/Guides
    • Tech Field Day
    • Interviews
  • Health
    • Food
    • Biohacking
    • Fitness
  • Faith
  • Book Notes
    • Business Books
    • Faith Books
    • Health Books
    • Technology Books
  • About
  • Show Search
Hide Search

Scheduled VM Reboots with PowerCLI

James Green · Jan 20, 2014 ·

Here’s a PowerCLI script that will read in a list of VMs, and then gracefully shut them down, wait a specified amount of time (5 minutes in this case) and then boot them again. Hope it helps!

[code language=”powershell”]

## Logging Function
Function Log ($logText){
$date = Get-Date
Add-Content -Path "C:Toolsreboots.log" -Value "$date $logText" -Force
}

## Load PowerCLI Modules
add-pssnapin VMware.VimAutomation.Core
Log("PowerCLI snap-in loaded")

## Import Credentials
$CredFile = "C:Toolscreds.xml"
$Cred = Get-VICredentialStoreItem -File $CredFile
Log("Imported VI credentials")

## Connect to vCenter server
$login = Connect-VIServer -Server <server> -User $Cred.User -Password $Cred.Password -WarningAction SilentlyContinue
Log("Connected to <server>")

## Read in List
$toRestart = Get-Content C:ToolsToRestart.txt
Log("Read in list. Rebooting:")
Log($toRestart)

## Shut down VMs
Write-Host "Stopping VMs…"
$toRestart | %{Shutdown-VMGuest $_ -Confirm:$false}
Log("Shut down all VMs")

## Pause for 5 minutes w/ countdown timer
Write-Host "Waiting 5 minutes…"
Log("Waiting 5 minutes")
$x = 5*60
$length = $x / 100
while($x -gt 0) {
$min = [int](([string]($x/60)).split(‘.’)[0])
$text = " " + $min + " minutes " + ($x % 60) + " seconds left"
Write-Progress "Waiting for VMs to shut down" -status $text -perc ($x/$length)
start-sleep -s 1
$x–
}
Log("5 minutes is up!")

## Boot VMs
Write-Host "Starting VMs…"
$toRestart | %{Start-VM $_}
Log("All VMs started. Finished successfully!")
[/code]

VMware automation, powercli

James Green is an enterprise IT consultant, a product of an amazing IT community, and a partner in ActualTech Media. He is a serial vExpert designee and a passionate Tech Field Day delegate and supporter. » Read Full Bio...

James Green: View My Blog Posts

Copyright © 2023 · Monochrome Pro on Genesis Framework · WordPress · Log in

Posting....