-
Notifications
You must be signed in to change notification settings - Fork 5
/
RemoveVM.ps1
39 lines (31 loc) · 1021 Bytes
/
RemoveVM.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Param($VMName = '')
$ErrorActionPreference = 'Stop'
$vmList = @{}
Get-VM | % {
$thisVM = $_
$hasDiffDisk = $false
$thisVM | Get-VMHardDiskDrive | Get-VHD | ? { $_.VhdType -eq 'Differencing' } | % {
$hasDiffDisk = $true
}
if ($hasDiffDisk) { $vmList.Add($thisVM.Name,$thisVM) }
}
# Get Template Name if not supplied
while (-not ($vmList.ContainsKey($VMName))) {
Write-Host "Remove VM"
$vmList.GetEnumerator() | % {
Write-Host "- $($_.Key)"
}
$VMName = Read-Host -Prompt "Enter VM Name"
}
$diskList = ($vmList.Item($VMName) | Get-VMHardDiskDrive | Get-VHD | % { Write-Output $_.Path })
Write-Host "Removing VM..."
$vmList.Item($VMName) | Stop-VM -Confirm:$false -Force -TurnOff -Save:$false -ErrorAction 'SilentlyContinue'
$vmList.Item($VMName) | Remove-VM -Confirm:$false -Force | Out-Null
Write-Host "Removing Disks..."
$diskList | % {
If (Test-Path -Path $_) {
$_ | Remove-Item -Force -Confirm:$false | Out-Null
} else {
Write-Host "Disk at $($_) is already removed "
}
}