VMware Cloud Community
Shahaf
Contributor
Contributor
Jump to solution

create a maintenance script

hi,

Is it possible to create a script that turn off a virtual machine that powered on for more than 5 days?

if yes i will appreciate some help with it.

Thanks!

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Sure, try something like this

$excluded = 'a','b','c'

$now = Get-Date

Get-VM |

where{$_.PowerState -eq 'PoweredOn' -and

  ($now - $_.ExtensionData.Runtime.BootTime).TotalDays -gt 5 -and

  $excluded -notcontains $_.Name} |

Get-VMGuest | Shutdown-VMGuest -Confirm:$false


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

View solution in original post

Reply
0 Kudos
3 Replies
LucD
Leadership
Leadership
Jump to solution

Try something like this

This uses a graceful shutdown of the guest OS, and assumes VMware Tools are installed.

An alternative is to use Stop-VM

$now = Get-Date

Get-VM | where{$_.PowerState -eq 'PoweredOn' -and ($now - $_.ExtensionData.Runtime.BootTime).TotalDays -gt 5} |

Get-VMGuest | Shutdown-VMGuest -Confirm:$false


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

Reply
0 Kudos
Shahaf
Contributor
Contributor
Jump to solution

one more question, is it possible to add an exception?

for example to turn off all the machines that powered on for 5 days except the following machines a, b, c.....

thanks!

Reply
0 Kudos
LucD
Leadership
Leadership
Jump to solution

Sure, try something like this

$excluded = 'a','b','c'

$now = Get-Date

Get-VM |

where{$_.PowerState -eq 'PoweredOn' -and

  ($now - $_.ExtensionData.Runtime.BootTime).TotalDays -gt 5 -and

  $excluded -notcontains $_.Name} |

Get-VMGuest | Shutdown-VMGuest -Confirm:$false


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

Reply
0 Kudos