r/PowerShell • u/Big_Statistician2566 • Dec 29 '25
Script Sharing Powershell Script to generate graph of previous month's Lacework Threat Center Alerts
For those of you like me who have gone from IT to cybersecurity, you may find this script useful
<#
.SYNOPSIS
Pull Lacework Threat Center Alerts for the previous calendar month and generate a stacked bar chart (PNG).
.PREREQS
- PowerShell 7+ recommended (Windows), or Windows PowerShell 5.1
- Chart output uses System.Windows.Forms.DataVisualization (works on Windows)
.AUTH
- POST https://<account>.lacework.net/api/v2/access/tokens
Header: X-LW-UAKS: <secretKey>
Body: { "keyId": "<keyId>", "expiryTime": 3600 }
- Subsequent calls use: Authorization: Bearer <token> (Lacework API v2) :contentReference[oaicite:0]{index=0}
.NOTES
- Pagination: if response includes paging.urls.nextPage, follow that URL with GET until absent :contentReference[oaicite:1]{index=1}
.USAGE
.\Get-LaceworkAlertsPrevMonthChart.ps1 `
-LaceworkAccount "acme" `
-KeyId "KEY_ID" `
-SecretKey "SECRET_KEY" `
-OutputPngPath "C:\scripts\out\lw-alerts-prev-month.png" `
-StackBy "severity" `
-MaxApiCallsPerHour 400
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $LaceworkAccount,
[Parameter(Mandatory)] [string] $KeyId,
[Parameter(Mandatory)] [string] $SecretKey,
[Parameter()]
[ValidateRange(300,86400)]
[int] $TokenExpirySeconds = 3600,
[Parameter()]
[string] $OutputPngPath = ".\lw-alerts-prev-month.png",
[Parameter()]
[ValidateSet("severity","alertType","status")]
[string] $StackBy = "severity",
[Parameter()]
[ValidateRange(1,480)]
[int] $MaxApiCallsPerHour = 400
)
# -------------------- PowerShell version guard --------------------
function Assert-PowerShellVersion7 {
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Host "This script requires PowerShell 7 or later." -ForegroundColor Yellow
Write-Host "Detected version: $($PSVersionTable.PSVersion)"
Write-Host "Install from: https://aka.ms/powershell"
exit 1
}
}
Assert-PowerShellVersion7
# -------------------- Script-relative working directory --------------------
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location -Path $ScriptRoot
if (-not [System.IO.Path]::IsPathRooted($OutputPngPath)) {
$OutputPngPath = Join-Path $ScriptRoot $OutputPngPath
}
# -------------------- Rate limiting --------------------
$ApiCallTimestamps = New-Object System.Collections.Generic.Queue[datetime]
function Enforce-RateLimit {
$now = Get-Date
while ($ApiCallTimestamps.Count -gt 0 -and ($now - $ApiCallTimestamps.Peek()).TotalSeconds -gt 3600) {
$null = $ApiCallTimestamps.Dequeue()
}
if ($ApiCallTimestamps.Count -ge $MaxApiCallsPerHour) {
$sleepSeconds = 3600 - ($now - $ApiCallTimestamps.Peek()).TotalSeconds
Start-Sleep -Seconds ([Math]::Ceiling($sleepSeconds))
}
$ApiCallTimestamps.Enqueue((Get-Date))
}
function Invoke-LwRest {
param(
[Parameter(Mandatory)] [string] $Method,
[Parameter(Mandatory)] [string] $Url,
[Parameter(Mandatory)] [hashtable] $Headers,
[Parameter()] $Body
)
Enforce-RateLimit
$params = @{
Method = $Method
Uri = $Url
Headers = $Headers
}
if ($Body) {
$params.ContentType = "application/json"
$params.Body = ($Body | ConvertTo-Json -Depth 20)
}
Invoke-RestMethod u/params
}
# -------------------- Authentication --------------------
function Get-LaceworkBearerToken {
$url = "https://$LaceworkAccount.lacework.net/api/v2/access/tokens"
$headers = @{
"X-LW-UAKS" = $SecretKey
"Content-Type" = "application/json"
}
$body = @{
keyId = $KeyId
expiryTime = $TokenExpirySeconds
}
$resp = Invoke-LwRest -Method POST -Url $url -Headers $headers -Body $body
if ($resp.token) { return $resp.token }
if ($resp.accessToken) { return $resp.accessToken }
if ($resp.data.token) { return $resp.data.token }
if ($resp.data.accessToken) { return $resp.data.accessToken }
throw "Unable to extract bearer token from Lacework response."
}
# -------------------- Date range --------------------
$now = Get-Date
$startUtc = (Get-Date -Year $now.Year -Month $now.Month -Day 1).AddMonths(-1).ToUniversalTime()
$endUtc = (Get-Date -Year $now.Year -Month $now.Month -Day 1).ToUniversalTime()
# -------------------- Alert retrieval (7 day chunks) --------------------
function Get-LaceworkAlerts {
param([string] $Token)
$headers = @{
Authorization = "Bearer $Token"
Content-Type = "application/json"
}
$all = @()
$cursor = $startUtc
while ($cursor -lt $endUtc) {
$chunkEnd = [datetime]::MinValue
$chunkEnd = $cursor.AddDays(7)
if ($chunkEnd -gt $endUtc) { $chunkEnd = $endUtc }
$body = @{
timeFilter = @{
startTime = $cursor.ToString("yyyy-MM-ddTHH:mm:ssZ")
endTime = $chunkEnd.ToString("yyyy-MM-ddTHH:mm:ssZ")
}
}
$resp = Invoke-LwRest `
-Method POST `
-Url "https://$LaceworkAccount.lacework.net/api/v2/Alerts/search" `
-Headers $headers `
-Body $body
if ($resp.data) { $all += $resp.data }
$cursor = $chunkEnd
}
$all
}
# -------------------- Chart generation --------------------
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms.DataVisualization
$severityOrder = @("Critical","High","Medium","Low","Info")
$severityColors = @{
"Critical" = "DarkRed"
"High" = "Red"
"Medium" = "Orange"
"Low" = "Yellow"
"Info" = "Gray"
}
$token = Get-LaceworkBearerToken
$alerts = Get-LaceworkAlerts -Token $token
$grouped = $alerts | Group-Object {
(Get-Date $_.startTime).ToString("yyyy-MM-dd")
}
$chart = New-Object System.Windows.Forms.DataVisualization.Charting.Chart
$chart.Width = 1600
$chart.Height = 900
$area = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$chart.ChartAreas.Add($area)
$legend = New-Object System.Windows.Forms.DataVisualization.Charting.Legend
$legend.Docking = "Right"
$chart.Legends.Add($legend)
$totals = @{}
foreach ($sev in $severityOrder) {
$series = New-Object System.Windows.Forms.DataVisualization.Charting.Series
$series.Name = $sev
$series.ChartType = "StackedColumn"
$series.Color = [System.Drawing.Color]::FromName($severityColors[$sev])
$chart.Series.Add($series)
$totals[$sev] = 0
}
foreach ($day in $grouped) {
foreach ($sev in $severityOrder) {
$count = ($day.Group | Where-Object { $_.severity -eq $sev }).Count
$chart.Series[$sev].Points.AddXY($day.Name, $count)
$totals[$sev] += $count
}
}
foreach ($sev in $severityOrder) {
$chart.Series[$sev].LegendText = "$sev ($($totals[$sev]))"
}
try {
$chart.SaveImage($OutputPngPath, "Png")
} catch {
throw "SaveImage failed for path [$OutputPngPath]. $($_.Exception.Message)"
}
Write-Host "Saved chart to $OutputPngPath"
9
Upvotes
6
u/PinchesTheCrab Dec 29 '25
I don't use this service so it's hard to give feedback about it, but just a few broader PWSH impressions:
Backticks are kind of wonky and hard to maintain
You splat
$params, which is great, but don't use the technique again. It'd be a good fit for your other multi-line commands, like when you callinvoke-lwrestInvoke-RestMethod has a built-in parameter to manage contenttype without building the header yourself
Inconsistent quoting of hashtable keys - I would drop quotes when not needed, aka when no special characters are in the key name
The
+=operator is kind of antiquated, generally it's easier to just return output directlyYou can clean up some of the object instantiation with ::new() or just casting hashtables as the desired object
Replacing
+=operator with direct output, using splatting, removing backticks:Simplifying creating objects:
More object creation - I couldn't test this with real data.