Hi,
I am unable to capture the correct output. when the VM is Powered Off already, still it is capturing Powered Off date.
Please help!!
Script
$VMList = Get-Folder MyVMs | Get-VM
$report = @()
foreach($vmName in $VMList){
$vm = Get-VM -Name $vmName
if($vm.Guest.State -eq "Running"){
Shutdown-VMGuest -VM $vm -Confirm:$false}
else{
Stop-VM -VM $vm -confirm:$false
}
Write-Host "Shutting Down $vmName at $(get-date)"
Start-Sleep 10
$report += New-Object PSObject -Property @{
'VM_Name' = $vmName
'Power_Off_Time' = Get-Date -Format 'MM/dd/yyyy HH:mm:ss'
}
}
$report | ft -auto
I'm not too sure I understand what you are trying to do here.
The Guest.State property can have the following values:
NotRunning |
Resetting |
Running |
ShuttingDown |
Standby |
Unknown |
When that state is 'Running' you shutdown the Guest OS.
In all other cases, you do a Stop-VM.
You could use the State 'NoTrunning' to detect VMs that are already powered off.
But that could also be the State for a VM where the VMware Tools are not running.
If I understand your intention correctly I would do something like this.
$report = @()
foreach($vm in $VMList){
if($vm.PowerState -eq 'PoweredOn'){
if($vm.Guest.State -eq "Running"){
Shutdown-VMGuest -VM $vm -Confirm:$false
}
else{
Stop-VM -VM $vm -confirm:$false
}
Write-Host "Shutting Down $vmName at $(get-date)"
Start-Sleep 10
$report += New-Object PSObject -Property @{
'VM_Name' = $vmName
'Power_Off_Time' = Get-Date -Format 'MM/dd/yyyy HH:mm:ss'
}
}
}
$report | ft -auto
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
I'm not too sure I understand what you are trying to do here.
The Guest.State property can have the following values:
NotRunning |
Resetting |
Running |
ShuttingDown |
Standby |
Unknown |
When that state is 'Running' you shutdown the Guest OS.
In all other cases, you do a Stop-VM.
You could use the State 'NoTrunning' to detect VMs that are already powered off.
But that could also be the State for a VM where the VMware Tools are not running.
If I understand your intention correctly I would do something like this.
$report = @()
foreach($vm in $VMList){
if($vm.PowerState -eq 'PoweredOn'){
if($vm.Guest.State -eq "Running"){
Shutdown-VMGuest -VM $vm -Confirm:$false
}
else{
Stop-VM -VM $vm -confirm:$false
}
Write-Host "Shutting Down $vmName at $(get-date)"
Start-Sleep 10
$report += New-Object PSObject -Property @{
'VM_Name' = $vmName
'Power_Off_Time' = Get-Date -Format 'MM/dd/yyyy HH:mm:ss'
}
}
}
$report | ft -auto
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
That worked
Thank you very much LucD.