Skip to content

Instantly share code, notes, and snippets.

Last active November 5, 2022 20:59
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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
# Track build time components below
$steps = [System.Collections.Generic.List[PSObject]]@()
function TrackTime {
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 }
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...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment