I created the following script to schedule some restart jobs overnight. The goal for this script was to add some parameters so you don’t have to edit the script file itself to schedule it for another VM or a group of VM’s.
#################################################################### # # Restart-VMs.ps1 # # -vCenter vCenter Server or Servers to connect to.
# Example -vCenter "vc01","vc02" # -vmName the VM or VMs to restart.
# Example -vmName "VM1" or -vmName "VM1","VM2" # # Example: #.\Restart-VMs.ps1 -vCenter vc01.ict-freak.local -vmName "VM1","VM2" # # Version 1.0 May 2010 Arne Fokkema www.ict-freak.nl @afokkema # ##################################################################### param( [parameter(Mandatory = $true)] [string[]]$vCenter, [parameter(Mandatory = $true)] [string[]]$vmName ) $VIServer = Connect-VIServer $vCenter If ($VIServer.IsConnected -ne $true){ Write-Host "error connecting to $vCenter" -ForegroundColor Red exit } foreach($vm in $vmName){ Write-Host "Going to restart $vm" Restart-VMGuest -VM (Get-VM $vm) -Confirm:$false } Disconnect-VIServer -Confirm:$false
Let’s start to run the script from the PowerCLI console first:
I started the script without setting any of the parameters. Since these two parameters are necessary to run the script, you will be asked to enter the parameters, before you can continue.
Now it’s time to schedule the script in Windows Server 2008. Just create a simple scheduled task with the following settings:
The first line below is the Program/script: setting. The second line is the Add arguments setting.
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe
-PSConsoleFile "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" " & "C:\Scripts\Restart-VMs.ps1" -vCenter vc01 -vmName "VM1","VM2"
When you are going to use this script, be absolutely sure you are allowed to restart the VM’s you scheduled.
Hi,
Nice script. but what if you want to reboot all your e.g VDI machines that have a display starting with VDI. with other words is it possible to use wild cards?
Greetings
Gert
Hi Gert,
You might want to modify the script, for example:
$vm = (Get-VM | where { $_.name -like “vdi*” })
Or maybe:
$vm = (Get-VM | where { $_.name -like “vdi*” -and $_.PowerState -eq “PoweredOn” })
Hi,
This is working fine now. But we see that sometimes the VM’s do not restart because of VMware tools are stopped running.
I am lookin in to it so that if a restart failes I do a reset.
Gert
All my VDI machine begin with “W”, So i just added “W*” and it went aharad and rebooted all machines stareting with W.
Brilliant!!
Thank you very much
thanks for sharing, it worked running directly from the PS console but does not run from task scheduler, neither throw any error or message.