Automation

 View Only
  • 1.  Remove VMs older than 14 days BUT the VM name changes!

    Posted Feb 18, 2021 12:56 AM

    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

     



  • 2.  RE: Remove VMs older than 14 days BUT the VM name changes!
    Best Answer

    Posted Feb 18, 2021 07:08 AM

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



  • 3.  RE: Remove VMs older than 14 days BUT the VM name changes!

    Posted Feb 24, 2021 11:14 PM

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

     

     

    Thanks for your help as always! 



  • 4.  RE: Remove VMs older than 14 days BUT the VM name changes!

    Posted Feb 25, 2021 07:26 AM

    You are right, sorry for the typo.