Last active
July 14, 2024 21:00
-
-
Save NickCraver/e1f477ef02e38bfb84d9b74e736ca070 to your computer and use it in GitHub Desktop.
Quick example of how to use script blocks to track timing in an easy-to-wrap way in PowerShell for things like stages of a build
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Track build time components below | |
$steps = [System.Collections.Generic.List[PSObject]]@() | |
function TrackTime { | |
Param( | |
[string]$name, | |
[scriptblock]$script | |
) | |
Write-Host "" | |
Write-Host -ForegroundColor Blue "[$(([DateTime](Get-Date)).ToString("u"))] Step: $name" | |
# Measure-Command doesn't stream output here so...can't use it. Do it the janky way. | |
$step = @{ Name = $name; Start = (Get-Date); Success = $true } | |
$steps.Add($step) | |
Invoke-Command -ScriptBlock $script | |
$step.Duration = New-TimeSpan -Start $step.Start -End (Get-Date) | |
} | |
function WriteFooter() { | |
Write-Host -ForegroundColor Blue "[Build Summary]" | |
Write-Host $("{0,-24} {1,-16} {2,8}" -F "Step", "StartTime", "Duration") | |
Write-Host "----------------------------------------------------------" | |
foreach ($step in $steps) { | |
if ($step.Success) { | |
Write-Host $("{0,-24} {1,-16} {2,8}s" -F $step.Name, $step.Start.ToString("hh:mm:ss.fff"), $step.Duration.TotalSeconds.ToString("0.00")) | |
} | |
else { | |
Write-Host -ForegroundColor Red $("{0,-24} {1,-16} {2,8}s" -F ($step.Name + " (Fail)"), $step.Start.ToString("hh:mm:ss.fff"), $step.Duration.TotalSeconds.ToString("0.00")) | |
} | |
} | |
$totalDuration = (Get-Date) - ($steps[0].Start) | |
Write-Host "----------------------------------------------------------" | |
Write-Host -ForegroundColor Green "Overall build time: $($totalDuration.ToString("hh\:mm\:ss\.fff")) (hh:mm:ss) = $($totalDuration.TotalSeconds.ToString("0.000")) sec" | |
Write-Host "" | |
} | |
# Your script! | |
TrackTime -Name "Init" -Script { | |
Write-Host "Initializing" | |
Start-Sleep -Seconds 2 | |
} | |
TrackTime -Name "Short nap" -Script { | |
Start-Sleep -Milliseconds 100 | |
# If you want to fail the current step: $steps[$steps.Count - 1].Success = $false | |
# ...and it would render red with (Fail) beside, still rendering the timings to help the user. | |
} | |
TrackTime -Name "Zzzzzzz" -Script { | |
Start-Sleep -Seconds 2 | |
} | |
## Print timings out at the end somewhere... | |
WriteFooter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment