Skip to content

Instantly share code, notes, and snippets.

@Graham-Beer
Created February 26, 2019 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Graham-Beer/1800c0423a107eff566b6014729d8415 to your computer and use it in GitHub Desktop.
Save Graham-Beer/1800c0423a107eff566b6014729d8415 to your computer and use it in GitHub Desktop.
# PowerShell script file to be executed as an AWS Lambda function.
#
# When executing in Lambda the following variables will be predefined.
# $LambdaInput - A PSObject that contains the Lambda function input data.
# $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment.
#
# The last item in the PowerShell pipeline will be returned as the result of the Lambda function.
#
# To include PowerShell modules with your Lambda function, like the AWSPowerShell.NetCore module, add a "#Requires" statement
# indicating the module and version.
#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.365.0'}
$instances = Get-EC2Instance -Filter @(
@{name = 'tag:power_off_by_script'; values = "true"}
@{name = 'instance-state-code'; values = 16}
)
foreach ($instance in $instances){
$InstanceId = $instance.Instances.InstanceId
Write-Host "Attempting to stop instance:" $($instanceId)
Stop-EC2Instance -InstanceId $InstanceId
Start-Sleep 5
if (-not (Get-EC2InstanceStatus -InstanceId $InstanceId).InstanceState.Name.Value) {
Write-Host "'$InstanceId' is switched off"
}
}
# Uncomment to send the input event to CloudWatch Logs
# Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment