-
Notifications
You must be signed in to change notification settings - Fork 3
/
Remove-Vm.ps1
73 lines (54 loc) · 1.78 KB
/
Remove-Vm.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
param
(
[Parameter(Mandatory=$true, HelpMessage="Name of lab to remove")]
[string] $DevTestLabName,
[Parameter(Mandatory=$true, HelpMessage="RG of lab to remove")]
[string] $ResourceGroupName,
[Parameter(Mandatory=$false, HelpMessage="ImagePattern of VM to remove")]
[string] $ImagePattern = "Windows - Lab",
[ValidateSet("Note","Name")]
[Parameter(Mandatory=$true, HelpMessage="Property of the VM to match by (Name, Note)")]
[string] $MatchBy,
[Parameter(valueFromRemainingArguments=$true)]
[String[]]
$rest = @()
)
$ErrorActionPreference = "Stop"
. "./Utils.ps1"
function Select-Vms {
param ($vms)
if($ImagePattern) {
$patterns = $ImagePattern.Split(",").Trim()
# Severely in need of a linq query to do this ...
$newVms = @()
foreach($vm in $vms) {
foreach($cond in $patterns) {
$toCompare = if($MatchBy -eq "Note") {$vm.Properties.notes} else {$vm.Name}
if($toCompare -like $cond) {
$newVms += $vm
break
}
}
}
if(-not $newVms) {
throw "No vm selected by the ImagePattern chosen in $DevTestLabName"
}
return $newVms
}
return $vms # No ImagePattern passed
}
Write-Host "Removing Vms from lab $DevTestLabName in $ResourceGroupName"
$vms = Get-AzureRmResource -ResourceType "Microsoft.DevTestLab/labs/virtualMachines" -ResourceGroupName $ResourceGroupName -ExpandProperties -Name "$DevTestLabName/"
$selectedVms = Select-Vms $vms
$jobs = @()
foreach($vm in $selectedVms) {
$Resid = $vm.ResourceId
Write-Host "Deleting $Resid"
$sb = [scriptblock]::create(
@"
Remove-AzureRmResource -ResourceId $Resid -Force
"@)
$jobs += Start-RSJob -ScriptBlock $sb -Name $vm.Name
Start-Sleep -Seconds 2
}
Wait-RSJobWithProgress -secTimeout (2 * 60 * 60) -jobs $jobs