VMware Cloud Community
AGFlora
Enthusiast
Enthusiast
Jump to solution

VM Last Poweron

Hi

I'm trying to get a list of the vm in my environment that were not poweredon in 30 days and the last time they were powered on but I seem to be only getting the vm that are powered off.

Thanks

$vms

= Get-VM | where {$_.PowerState -eq "PoweredOff"}

$vmPoweredOff

= $vms | %{$_.Name}

$events

= Get-VIEvent -Start (Get-Date).AddDays(-30) -Entity $vms | where{$_.FullFormattedMessage -like "*is powered off"}

$lastMonthVM

= $events | %{$_.Vm.Name}

$vmPoweredOff

| where {!($lastMonthVM -contains $_)}

 

# Get a VM's last power on date based on the VM's events.

# Requires PowerCLI 4.0 and PowerShell v2.

function

Get-LastPowerOn {

param(

[Parameter(

Mandatory

=$true,

ValueFromPipeline

=$true,

HelpMessage

="VM"

)]

[

VMware.VimAutomation.Types.VirtualMachine]

$VM

)

Process {

# Patterns that indicate an attempt to power a VM on. This differ

# across versions and likely across language. Please add your own

# if you find one missing.

$patterns = @(

"*Power On virtual machine*", # vCenter 4 English

"*is starting*" # ESX 4/3.5 English

)

$events = $VM | Get-VIEvent

$qualifiedEvents = @()

foreach ($pattern in $patterns) {

$qualifiedEvents += $events | Where { $_.FullFormattedMessage -like $pattern }

}

$qualifiedEvents = $qualifiedEvents | Where { $_ -ne $null }

$sortedEvents = Sort-Object -InputObject $qualifiedEvents -Property CreatedTime -Descending

$event = $sortedEvents | select -First 1

$obj = New-Object PSObject

$obj | Add-Member -MemberType NoteProperty -Name VM -Value $_

$obj | Add-Member -MemberType NoteProperty -Name PowerState -Value $_.PowerState

$obj | Add-Member -MemberType NoteProperty -Name LastPoweron -Value $null

if ($event) {

$obj.LastPoweron = $event.CreatedTime

}

Write-Output $obj

}

}

$Vms | Get-LastPowerOn | Export-Csv LastPowerOn.csv -NoTypeInformation -UseCulture

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try it like this

Select @{N="VM";E={$_.Vm.Name}},CreatedTime,UserName, 
@
{N="Department";E={(Get-VM $_.Vm.Name).CustomFields.Item("Department")}}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

Reply
0 Kudos
20 Replies
LucD
Leadership
Leadership
Jump to solution

Have a look at Events – Part 5 : Powered off for more than 1 week ?

Replace the 7 days with 30 days


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Hi Luc

I did read your article and that's where I got the code from at the top of this post.

Maybe my question should be how do I add the last time the vm was powered on?

Thanks

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

I meant something like this

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff"}
$vmPoweredOff = $vms | %{$_.Name}
$events = Get-VIEvent -Start (Get-Date).AddDays(-31) -Entity $vms -MaxSamples ([int]::MaxValue) | 
    where{$_.FullFormattedMessage -like "*is powered off"}
$lastweekVM = $events | %{$_.Vm.Name}
$vmPoweredOff | where {!($lastweekVM -contains $_)}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Luc

How can I take your script:

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff"}
$vmPoweredOff = $vms | %{$_.Name}
$events = Get-VIEvent -Start (Get-Date).AddDays(-31) -Entity $vms -MaxSamples ([int]::MaxValue) | 
    where{$_.FullFormattedMessage -like "*is powered off"}
$lastweekVM = $events | %{$_.Vm.Name}
$vmPoweredOff | where {!($lastweekVM -contains $_)}


...and find out when was the last time the vm that have been powered down for 30 days powered on?

Maybe make your script into a function and the code that get's the powred on date into a function as well then pass the vm names to the function?
Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Ok, so if I get the question correctly you want to find out for the currently powered off VMs when they were last powered on and that should be more than 30 days ago ?

The attached script uses my Get-VIEventPlus function from my Get the vMotion/svMotion history post to find these.

Have a look.

Using a function that does this VM per VM would take forever I'm afraid.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Hi Luc

Actually i need the following:

1. all vm that have not been powered on for 30 days or more

2. the last time these vm that have not been powered on for 30 days or more-the last time they were powered on

3. vm Owner annotation

vm  LastPowerOn Owner

----  ------------------- ----------

How difficult is it to list the owner annotation for each vm to this script?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Try changing the last line from

Select @{N="VM";E={$_.Vm.Name}},CreatedTime

to

Select @{N="VM";E={$_.Vm.Name}},CreatedTime,UserName


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Thanks this worked...

Select @{N="VM";E={$_.Vm.Name}},CreatedTime,UserName

So let me make sure I understand what's going on here...

Your script finds all the vm that have not been powered on for 30 days or more and lists the vm name, last time the vm was powered on, and now the user name. Is that correct?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

That is correct


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Great!

One last question if I may...

I'm trying to get a custom attribute but the following does not work:

Select

@{N="VM";E={$_.Vm.Name}},CreatedTime,UserName,@{N="Department";E={$_.CustomFields.Item("Department")}}

What am I doing wrong?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Try it like this

Select @{N="VM";E={$_.Vm.Name}},CreatedTime,UserName, 
@
{N="Department";E={(Get-VM $_.Vm.Name).CustomFields.Item("Department")}}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Thanks again...I'm set now.

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

The script works great with the exception that one vm turned up in the report that wasn't quite powered off for 30 days...

2/17/2013 8:53

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Do you know when it was last powered off ?

You could look with

$vm = Get-VM -Name ThatVM

$events = Get-VIEvent -Start (Get-Date).AddDays(-31) -Entity $vm -MaxSamples ([int]::MaxValue) |
   where{$_.FullFormattedMessage -like "*is powered off"}
$events

if there was a poweroff in the last 31 days.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
AGFlora
Enthusiast
Enthusiast
Jump to solution

Ah...My bad....it was powered off....CreatedTime          : 3/22/2013 10:05:43 PM

Hey can we add the powered off event to the report and would it cause the script to run a lot longer?

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

That CreatedTime indicates the time when the event was logged, so that shouldn't be too far off from the actual power off time.

I don't know if there is a source where one could get a more precise time.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

AGFlora
Enthusiast
Enthusiast
Jump to solution

OK thanks again!

Reply
0 Kudos
raffic_ncc
Enthusiast
Enthusiast
Jump to solution

Thanks Much !!!!

Mohammed Raffic

http://www.vmwarearena.com

Mohammed Raffic VCP4,VCP5,VCAP4-DCA,VCAP5-DCA,VCP-Cloud, MCSA.MCTS,CCA http://www.vmwarearena.com
Reply
0 Kudos
chicojr
Enthusiast
Enthusiast
Jump to solution

I run this:

   param(

    [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl[]]$Entity,

    [string[]]$EventType,

    [DateTime]$Start,

    [DateTime]$Finish,

    [switch]$Recurse,

    [switch]$FullMessage = $false

  )

  process {

    $eventnumber = 100

    $events = @()

    $eventMgr = Get-View EventManager

    $eventFilter = New-Object VMware.Vim.EventFilterSpec

    $eventFilter.disableFullMessage = ! $FullMessage

    $eventFilter.entity = New-Object VMware.Vim.EventFilterSpecByEntity

    $eventFilter.entity.recursion = &{if($Recurse){"all"}else{"self"}}

    $eventFilter.eventTypeId = $EventType

    if($Start -or $Finish){

      $eventFilter.time = New-Object VMware.Vim.EventFilterSpecByTime

      $eventFilter.time.beginTime = $Start

      $eventFilter.time.endTime = $Finish

    }

    $entity | %{

      $eventFilter.entity.entity = $_.ExtensionData.MoRef

      $eventCollector = Get-View ($eventMgr.CreateCollectorForEvents($eventFilter))

      $eventsBuffer = $eventCollector.ReadNextEvents($eventnumber)

      while($eventsBuffer){

        $events += $eventsBuffer

        $eventsBuffer = $eventCollector.ReadNextEvents($eventnumber)

      }

      $eventCollector.DestroyCollector()

    }

    $events

}

}

$oneMonth = (Get-Date).AddDays(-31)

$entity = Get-Folder -Name datacenters

$events = Get-VIEventPlus -Entity $entity -EventType VmPoweredOnEvent -Recurse -FullMessage

$events | Group-Object -Property {$_.Vm.Name} | %{

$_.Group | Sort-Object -Property CreatedTime -Descending |

Select -First 1 |

where {$_.CreatedTime -lt $oneMonth -and (Get-VM -Name $_.Vm.Name -ErrorAction SilentlyContinue).PowerState -eq "PoweredOff"} |

Select @{N="VM";E={$_.Vm.Name}},CreatedTime,UserName

}

But it errors out:

At line:38 char:1

+ }

+ ~

Unexpected token '}' in expression or statement.

    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException

    + FullyQualifiedErrorId : UnexpectedToken

I tried to clean up } but still fails, just need this to run cleanly and export to something viewable like a CSV please.

Reply
0 Kudos