VMware Cloud Community
Hetfield84
Enthusiast
Enthusiast
Jump to solution

Remove VMs older than 14 days BUT the VM name changes!

Hi,

We have a step in our decomm process where we rename a VM, appending _decomm at the end. For example if we were decommissioning a server named "test" we would go through the decomm steps, power it down and rename it "test_decomm".

I'm trying to write a script using some code by LucD that will delete all the VMs with *deco* in the name (in case someone only adds one m to the name, like "test_decom"). However, the challenge is the name change.

When I run the code below, it pulls events from before the server was renamed. Instead of deleting just the ones that have been off for 14 days or more, it deletes all the VM in the $vms variable.

The code is below. What am I doing wrong?

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff" -and $_.Name -like "*deco*"}
$vmPoweredOff = $vms | %{$_.Name}
$events = Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vmPoweredOff | where{$_.FullFormattedMessage -like "*is powered off"}
$lastweekVM = $events | %{$_.Vm.Name}
$vmPoweredOff = $vmPoweredOff | where {!($lastweekVM -contains $_)}

Remove-VM -VM $vmPoweredOff -DeletePermanently -Confirm:$false

 

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Can you try like this?
Only remove the WhatIf switch when you are sure the correct VMs are selected.

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff" -and $_.Name -match "_deco"}
$events = Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vms | where{$_ -is [VMware.Vim.VmPoweredOff]}

$selectedVMS = $vms | where{$events.Vm.Name -notcontains $_.Name}

Remove-VM -VM $selectedVMS -DeletePermanently -Confirm:$false -WhatIf


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

View solution in original post

3 Replies
LucD
Leadership
Leadership
Jump to solution

Can you try like this?
Only remove the WhatIf switch when you are sure the correct VMs are selected.

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff" -and $_.Name -match "_deco"}
$events = Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vms | where{$_ -is [VMware.Vim.VmPoweredOff]}

$selectedVMS = $vms | where{$events.Vm.Name -notcontains $_.Name}

Remove-VM -VM $selectedVMS -DeletePermanently -Confirm:$false -WhatIf


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

Hetfield84
Enthusiast
Enthusiast
Jump to solution

Great, that worked with one slight change. It's VmPoweredOffEvent not VmPoweredOff, so like this:

 

$events = Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vms | where{$_ -is [VMware.Vim.VmPoweredOffEvent]}

 

Thanks for your help as always! 

0 Kudos
LucD
Leadership
Leadership
Jump to solution

You are right, sorry for the typo.


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

0 Kudos