Gaprofitt17
Enthusiast
Enthusiast

Script to Power off VM's and Permanently Delete them

I've been trying this with no luck.  My CSV file has Server Name in the first column and all the VM's below..

Import-Csv C:\scripts\input.csv | ForEach-Object{

    $vmTmp = Get-VM $_."Server Name" -ErrorAction SilentlyContinue

    if ($vmTmp) {

        ## if the VM is on, power it off

        if ($vmTmp.PowerState -eq "PoweredOn") {Stop-VM $vmTmp -Confirm:$false}

        Remove-VM -VM $vmTmp -DeletePermanently -Confirm:$false -RunAsync

    } ## end if

    else {<# ...do nothing -- no VM by this name #>}

} ## end foreach-object

Get-VM : 10/24/2019 4:05:45 PM  Get-VM          VM with name 'laecoyy003q ' was not found using the specified filter(s).

At C:\scripts\vmstodecomm.ps1:2 char:14

+     $vmTmp = Get-VM $_."Server Name"

+              ~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException

    + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

The VM exists..

PS C:\scripts> Get-VM -Name laecoyy003q

Name                 PowerState Num CPUs MemoryGB

----                 ---------- -------- --------

laecoyy003q          PoweredOn  2        8.000

0 Kudos
1 Reply
LucD
Leadership
Leadership

Looks like you have a space at the end of the entry in the CSV.

VM with name 'laecoyy003q ' was not found


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

0 Kudos