PowerShell Token Bucket Rate Limiter Class
PowerShell
class TokenBucket {
[double]$Rate
[double]$Capacity
[double]$Tokens
[datetime]$Last
TokenBucket([double]$rate, [double]$capacity) {
$this.Rate = $rate; $this.Capacity = $capacity; $this.Tokens = $capacity
$this.Last = [datetime]::UtcNow
}
[bool] TryTake([int]$count = 1) {
$now = [datetime]::UtcNow
$elapsed = ($now - $this.Last).TotalSeconds
$this.Tokens = [Math]::Min($this.Capacity, $this.Tokens + $elapsed * $this.Rate)
$this.Last = $now
if ($this.Tokens -lt $count) { return $false }
$this.Tokens -= $count
return $true
}
}