PoshCode Archive  Artifact Content

Artifact 1b5f4f18babaebd235a4eb2d579d3b7ae8ff04f9066c5a496c129f64a2223f56:

  • File Report-DecomVMs.ps1 — part of check-in [c6a0342d38] at 2018-06-10 13:25:52 on branch trunk — Use this to view VM that have been decommissioned and turned off for more than 2 weeks so that they can be deleted. (user: Clint Jones size: 1859)

# encoding: ascii
# api: powershell
# title: Report-DecomVMs
# description: Use this to view VM that have been decommissioned and turned off for more than 2 weeks so that they can be deleted. 
# version: 0.1
# author: Clint Jones
# license: CC0
# x-poshcode-id: 3450
# x-archived: 2012-06-13T22:10:03
# x-published: 2012-06-08T11:38:00
#
# *Note (In our environment, we tag a “DNR” to the server name in vCenter once it is turned off for decom, simply remove that item if it does not apply to your environment)
#
#========================================================================
# Created on:   6/8/2012 9:45 AM
# Created by:   Clint Jones
# Organization: Virtually Genius!
# Filename:     Report-DecomVMs
#========================================================================

#Load PowerCLI
Add-PSSnapin VMware.VimAutomation.Core

#Connect to vCenter
Connect-VIServer -Server <viserver> -Credential (Get-Credential)

#variables
$deletenow = @()
$deletesoon = @()

#Check to see what VMs are labeled DNR and have been powered off
$dnrvms = Get-VM | Where-Object {($_.Name.Contains("DNR")) -and ($_.PowerState -eq "PoweredOff")}

foreach ($dnrvm in $dnrvms)
{

    #Make sure that the VM has been powered off for more than 14 days
    [array]$poweroffs = Get-VM -Name $dnrvm.Name | Get-VIEvent -Start (Get-Date).AddDays(-14) | Where-Object {$_.FullFormattedMessage -like "*is powered off"}
    
    if ($poweroffs -eq $null)
    {
      #this vm has been off more than 14 days - take action
      $deletenow += $dnrvm.Name
    }
    else
    {
      #this vm has not been off more than 14 days - report but do not take action
      $deletesoon += $dnrvm.Name
    }
 
}

#Remove duplications
$deletesoon = $deletesoon | Select-Object -Unique
$deletenow = $deletenow | Select-Object -Unique