-
Notifications
You must be signed in to change notification settings - Fork 0
/
EC2.Stop.ps1
94 lines (67 loc) · 2.51 KB
/
EC2.Stop.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#Set Root Dir
$RunDir = Split-path -Parent $MyInvocation.MyCommand.Definition
#Load Config
$Config = (Get-Content $RunDir\aws.json) -join "`n" | ConvertFrom-Json
#Load AWS PowerShell
if (!(Get-Module AWSPowerShell)) {
Import-Module AWSPowerShell
}
Import-Module "$RunDir\Modules\functions" -DisableNameChecking
Log "Functions Loaded" "Yellow"
## END AWSPowerShell BoilerPlate Code ###
Log "Getting Active EC2 Instances"
[array]$ActiveEC2 = Get-EC2Instance | Where-Object {
$_.Instances.State.Name -ne "terminated"
}
Log "Found: $($ActiveEC2.Count) Instances" "Green"
Log "Appending Name and State Info..."
ForEach ($instance in $ActiveEC2.Instances) {
$Name = if ($instance.Tag | Where-Object {$_.Key -eq "Name"}) {
($instance.Tag | Where-Object {$_.Key -eq "Name"}).Value
}
else {
"Null"
}
$instance | Add-Member Name($Name) -Force
$state = $Instance.State.Name.Value
$Instance | Add-Member State($State) -Force
}
$ActiveEC2.Instances | Format-Table Name, InstanceId, InstanceType, PrivateIPAddress, PublicIpAddress, VpcId, State
Log "Stopping Instances..."
ForEach ($instance in $ActiveEC2.Instances) {
Log "Stopping Instance $($instance.Name) : $($Instance.InstanceId)" "Yellow"
$StopEC2 = Stop-EC2Instance -InstanceId $instance.InstanceId
}
Log "Verifying Instance State..."
[array]$InstanceRunning = Get-EC2Instance | Where-Object {
$_.Instances.State.Name -ne "stopped" -and
$_.Instances.State.Name -ne "terminated"
}
Log "Instances Running: $($instanceRunning.Count)" "White"
While ($InstanceRunning.Count -gt 0) {
Start-Sleep -Seconds 5
Log "Verifying Instance State..."
[array]$InstanceRunning = Get-EC2Instance | Where-Object {
$_.Instances.State.Name -ne "stopped" -and
$_.Instances.State.Name -ne "terminated"
}
Log "Instances Running: $($instanceRunning.Count)" "White"
}
Log "Getting Active EC2 Instances"
[array]$ActiveEC2 = Get-EC2Instance | Where-Object {
$_.Instances.State.Name -ne "terminated"
}
Log "Found: $($ActiveEC2.Count) Instances" "Green"
Log "Appending Name and State Info..."
ForEach ($instance in $ActiveEC2.Instances) {
$Name = if ($instance.Tag | Where-Object {$_.Key -eq "Name"}) {
($instance.Tag | Where-Object {$_.Key -eq "Name"}).Value
}
else {
"Null"
}
$instance | Add-Member Name($Name) -Force
$state = $Instance.State.Name.Value
$Instance | Add-Member State($State) -Force
}
$ActiveEC2.Instances | Format-Table Name, InstanceId, InstanceType, PrivateIPAddress, PublicIpAddress, VpcId, State