VMware Cloud Community
HrcoCro
Contributor
Contributor

Delete powerd off vms

Hi, I hope that you could help me with my script

I need a script that would delete vms' that are located in specific folder and would send an email which vm's have been deleted.

I found this script, but I don't know how edit it to delete vm's just from specific folder that have been powered off for more then 14 days.

$vms = @{}

Get-VM | where {$_.PowerState -eq "PoweredOff"| % {$vms.Add($_.Name, $_)}

Get-VIEvent -Start (Get-Date).AddDays(-14-Entity $vms.Values -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOffEvent]|

  Sort-Object -Property CreatedTime -Unique | % {

  $vms.Remove($_.VM.Name)

}

 

Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false -WhatIf

 

$sMail = @{

  From   = 'virtualadmin@company.com'

  To   = 'vadmin@company.com'

  SmtpServer = 'smtprelay.company.com'

  Subject   = "Removed $($vms.Keys.Count) VM powered off more than 14 days"

  Body   = ($vms.Keys | Out-String)

}

 

Send-MailMessage @smail

 

0 Kudos
2 Replies
LucD
Leadership
Leadership

Just start with

Get-Folder -Name MyFolder | Get-VM | ...


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

0 Kudos
HrcoCro
Contributor
Contributor

Tnx LucD!

Tags (1)
0 Kudos