Function powerdownVM($Computername, $Hypervisor, [switch]$graceful, [switch]$Force, [switch]$StartVM ){
$vm = get-vm -computername $($hypervisor) |? {$_.name -like "*$($computername)*"}
if ($vm.name -eq "$($computername)"){
if ($graceful.IsPresent){
write-host "Gracefully shuttingdown ... $($computername)"
$vm|stop-vm -Force -whatif
}
if ($Force.IsPresent){
write-host "Forcing $($computername) to poweroff"
$vm|stop-vm -TurnOff -whatif
}
if ($StartVM.IsPresent) {
write-host "Starting $($computername)"
$vm|start-vm -name $computername -whatif
}
}
}
$computers = import-csv "c:\temp2\Computers.csv"
<# CSV with three columns
Name,Hypervisor,typeofshutdown
typeofshutdown can support 2 values :
Graceful, Force
#>
Function powerdownVM($Computername, $Hypervisor, [switch]$graceful, [switch]$Force, [switch]$StartVM ) {
$vm = get-vm -computername $($hypervisor) |? {$_.name -like "*$($computername)*"}
if ($vm.name -eq "$($computername)") {
if ($graceful.IsPresent) {
write-host "Gracefully shuttingdown ... $($computername)"
$vm| Shutdown-VMGuest -whatif
}
if ($Force.IsPresent) {
write-host "Forcing $($computername) to poweroff"
Function Kill-VM {
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
$VM, $KillType
)
PROCESS {
if ($VM.PowerState -eq "PoweredOff") {
Write-Host "$($VM.Name) is already Powered Off"
}
Else {
$esxcli = Get-EsxCli -vmhost ($VM.VMHost)
$WorldID = ($esxcli.vm.process.list() | Where { $_.DisplayName -eq $VM.Name}).WorldID
if (-not $KillType) {
$KillType = "soft"
}
$result = $esxcli.vm.process.kill($KillType, $WorldID)
if ($result -eq "true") {
Write-Host "$($VM.Name) killed via a $KillType kill"
}
Else {
$result
}
}
}
}
$vm |Kill-VM -KillType Hard -whatif
}
if ($StartVM.IsPresent) {
write-host "Starting $($computername)"
$vm|start-vm
}
}
}
foreach ($comp in $computers){
if ($comp.typeofshutdown -eq "Graceful"){
. PowerdownVM -computername $($comp.Name) -Hypervisor $($comp.Hypervisor) -graceful
}
if ($comp.typeofshutdown -eq "Force"){
. PowerdownVM -computername $($comp.Name) -Hypervisor $($comp.Hypervisor) -force
}
}
https://pubs.vmware.com/vsphere-51/index.jsp?topic=%2Fcom.vmware.powercli.cmdletref.doc%2FShutdown-VMGuest.html
https://www.vmware.com/support/developer/PowerCLI/PowerCLI41/html/Shutdown-VMGuest.html