Crisply report on script duration

While scripts can get written in a jiffy, it’s best to make them usable and functional as a foundation for operability.

Some scripts can take time to execute.  As a habit, I tend to build into my scripts a crisp and clear report on script duration; both to console and to a logfile.

Let’s declare a logfile, and output the start of the script; let’s capture the start time of the script run, and output it to console and logfile at the start of the script run:

$startTime = get-date
write-host  "STARTING: $($startTime) Script: $($MyInvocation.MyCommand.Definition)"
Add-Content $mylogfile "STARTING: $($startTime) Script: $($MyInvocation.MyCommand.Definition)"

At the end, let’s do the same; output the duration of the script run to console and logfile:

$endtime = Get-Date
Write-Host "Started script at $($starttime), Ended script at $($endtime), duration of $($endtime.Subtract($starttime).minutes) minutes and $($endtime.Subtract($starttime).seconds) seconds "
Add-Content $mylogfile "Started Script: $($MyInvocation.MyCommand.Definition) at $($starttime), Ended script at $($endtime), duration of $($endtime.Subtract($starttime).minutes) minutes and $($endtime.Subtract($starttime).seconds) seconds "

Simple as that. Reuse wherever needed.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *