Skip to content

Instantly share code, notes, and snippets.

@immanuelpotter
Last active September 4, 2019 15:31
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 immanuelpotter/03e1084ed67effb61070d0b434188e97 to your computer and use it in GitHub Desktop.
Save immanuelpotter/03e1084ed67effb61070d0b434188e97 to your computer and use it in GitHub Desktop.
RAM-free-cloudwatch-custom-metric-powershell
$action = New-ScheduledTaskAction -Execute "powershell" -Argument " we -File C:\Users\Administrator\Documents\WindowsPowerShell\write-ram-cw-custom-metric.ps1 -ExecutionPolicy bypass"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1)
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "CustomRAMCloudWatchMetricWrite" -Description "Logging percentage free memory to CloudWatch for this instance"
# Install Modules for AWS
Install-Module -Name AWSPowerShell.NetCore -AllowClobber -Force
# Get instance ID from metadata for later
$wc = New-Object System.Net.WebClient;
$instanceIdResult = $wc.DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
# Get OS Memory data
$os = Get-CimInstance Win32_OperatingSystem
$pctFree = [math]::Round(($os.FreePhysicalMemory/$os.TotalVisibleMemorySize)*100,2)
# Formulate the CW Metric object, pass dimensions to find it
$Metric = [Amazon.CloudWatch.Model.MetricDatum]::new()
$Dimension = [Amazon.CloudWatch.Model.Dimension]::new()
$Dimension.Name = 'InstanceId'
$Dimension.Value = $instanceIdResult
$Metric.Dimensions = $Dimension
$Metric.MetricName = 'MemoryPctFree'
$Metric.Value = $pctFree
# Send up to CW
Write-CWMetricData -MetricData $Metric -Namespace AWS/EC2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment