Six Million Ways To…
  • About
ESXi , Powercli

VM : Quickly delete one or more VM

by Axel March 11, 2019 No Comments

Hi guys,

In my labs I often have to provision a lot of “trashable” VMs and I wanted to run a single command to remove them easily.

From this idea I wrote a small script :

clear
$ExpectedPowerStatus = "PoweredOff"
$VMName = read-host 'Type the name of the VM to delete. If more than one VM are expected, use the wildcard "*"'
write-host $VMName -ForegroundColor Yellow

function getVMPowerStatus()
{
    param([parameter(mandatory=$true)]$vm)
    write-host "Function getVMPowerStatus:Getting Power state for VM $vm" -ForegroundColor DarkYellow$VMstate = (get-vm $vm).PowerState
    write-host "> Power state of $vm : is $VMstate"
    if($VMState -ne $ExpectedPowerStatus)
    {
        return $false
    }
}

function PowerOffVM()
{
    param([parameter(mandatory=$true)]$vm)
    write-host "Function PowerOffVM:Terminating VM $vm" -ForegroundColor DarkYellow
    try
    {
        stop-vm $vm -confirm:$false -ErrorAction stop
        write-host "> turned off successfully" -ForegroundColor Greenreturn $true
    }
    catch
    {
        write-host "> Failed to turn off VM" -ForegroundColor Red
    }
}

function DeleteVM()
{
    param([parameter(mandatory=$true)]$vm)
    write-host "Function DeleteVM:Preparing to delete VM $vm" -ForegroundColor DarkYellow
    $IsPoweredOff=getVMPowerStatus($vm)
    if($IsPoweredOff -ne $True)
    {
        PowerOffVM $vm
    }
    try
    {
        get-vm -Name $vm | Remove-VM -DeletePermanently -confirm:$false -ErrorAction stop
        write-host "> VM deleted successfully" -ForegroundColor Green
    }catch
    {
        write-host "> VM deletion failed" -ForegroundColor Red
    }
}

function Main()
{
    $VMtoDelete = @(get-vm $VMName)
    foreach($vm in $VMtoDelete){DeleteVM -vm $vm}
}

Main

From your powercli console, if not already done, connect to your vCenter/ESX and run the script

PowerCLIvCentervSphere

  • Previous vRO: Using vRA REST API to get all vCAC VMs4 years ago
  • Next vRO: Setting constants for workflows4 years ago

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Menu

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Recent Posts

  • vRA : API : Submit a request
  • vRO: Setting constants for workflows
  • VM : Quickly delete one or more VM
  • vRO: Using vRA REST API to get all vCAC VMs
  • vRO : Workflow to Get Restarted VMs by HA

Archives

  • October 2019
  • March 2019
  • March 2018
  • September 2017

Categories

  • CLI (2)
  • ESXi (1)
  • Orchestrator (4)
  • Scripts (3)
    • Powercli (3)
  • vRA (2)
  • vSphere (1)

Tags

API (1) CLI (1) HA (1) Nutanix (1) PowerCLI (1) Reminder (1) REST (1) REST API (1) vCenter (3) VRA (2) VRO (3) vSphere (4)
2023 Six Million Ways To…. Donna Theme powered by WordPress