<#
.SYNOPSIS
This script is used to powerdown and powerup a virtual machine on an ESXI host (Luben Kirov)
.PARAMETER vname
The name Of the virtual machine
.PARAMETER vmhost
The name of the virtual machine host(ESXI)
.PARAMETER username
The username used to log into the ESXI server
.PARAMETER keyfile
The location of the private key
.EXAMPLE
Powercycle.ps1 -vmname MyTestVm -vmhost "test-esxi01" -username root -keyfile private1
#>
param([string]$vmname = "vmname", [string]$vmhost = "vmhost", [string]$username = "username", [string]$keyfile = "keyfile")
Import-Module SSH-Sessions #import the powershell module
#Disconnect session in case one is opened
remove-sshsession -computername $vmhost
#Connect to ESXI host
new-SSHSession -computername $vmhost -username $username -KeyFile $keyfile
#Check and get the vm id, if vm does not exist exit
$result = invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/getallvms|grep -i $vmname" -quiet
$test = $result.split(" ")
$vmid = $test[0]
If ($vmid -eq ""){
Write-Host " VM not found on host"
remove-sshsession -computername $vmhost
exit 1
}
#Check vm power state if powered on power off the vm
$vmPowerState = invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/power.getstate $vmid |grep Powered" -quiet
if ($vmPowerState -eq "Powered on"){
invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/power.off $vmid" -quiet
$VMtoolsNot = "False"
$VMtoolsNotc = 0
While($VMtoolsNot -eq "False"){
If ($VMtoolsNotc -eq 40){
Write-Host " VM did not power down in 120 seconds, exiting"
remove-sshsession -computername $vmhost
exit 1
}
$VMtoolsNotResult = invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/get.summary $vmid |grep toolsRunningStatus" -quiet
$VMtoolsNotResult1 = $VMtoolsNotResult.split('"')
If($VMtoolsNotResult1[1] -eq "guestToolsNotRunning"){
$VMtoolsNot = "True"
Write-Host " VM Powered Down"
}else{
Start-Sleep -s 3
$VMtoolsNotc++
}
}
}
#Power on the Vm
invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/power.on $vmid" -quiet
$VMtools = "False"
$VMtoolsc = 0
While($VMtools -eq "False"){
If ($VMtoolsc -eq 40){
Write-Host " VM did not start in 120 seconds exiting"
remove-sshsession -computername $vmhost
exit 1
}
$VMtoolsResult = invoke-sshcommand -computername $vmhost -command "vim-cmd vmsvc/get.summary $vmid |grep toolsRunningStatus" -quiet
$VMtoolsResult1 = $VMtoolsResult.split('"')
If($VMtoolsResult1[1] -eq "guestToolsRunning"){
$VMtools = "True"
Write-Host " VM Powered Up"
}else{
Start-Sleep -s 3
$VMtoolsc++
}
}
#Disconnect session
remove-sshsession -computername $vmhost
exit 0