I am currently working on a powershell script where I need to measure the duration between the start and the end of the script execution. After searching for a while I decided to use this approach to do so: https://stackoverflow.com/a/61432373/11425760 I have one Get-Date call to get the start time at the beginning of the script execution and another Get-Date call right before the script execution is about to end:
$StartTime = Get-Date
# Script logic...
$EndTime = Get-Date
$Duration = New-TimeSpan -Start $StartTime -End $EndTime
$Day = switch ($Duration.Days)
{
0 { $null; break }
1 { "{0} day," -f $Duration.Days; break }
Default {"{0} days," -f $Duration.Days}
}
$Hour = switch ($Duration.Hours)
{
#0 { $null; break }
1 { "{0} hour," -f $Duration.Hours; break }
Default { "{0} hours," -f $Duration.Hours }
}
$Minute = switch ($Duration.Minutes)
{
#0 { $null; break }
1 { "{0} minute," -f $Duration.Minutes; break }
Default { "{0} minutes," -f $Duration.Minutes }
}
$Second = switch ($Duration.Seconds)
{
#0 { $null; break }
1 { "{0} second" -f $Duration.Seconds; break }
Default { "{0} seconds" -f $Duration.Seconds }
}
Write-Host "The script execution took: $Day $Hour $Minute $Second"
Write-Host "Script execution ended"
While this seemed to work fine when I implemented it, I suddenly started running into a problem where for some reason I get a "ParameterBindingException" when calling New-TimeSpan, telling me that the value for the "End" argument (e.g. "08/19/2020 08:54:51") cannot be converted into the type System.DateTime. When I then look at the start and end time I provided, they are both printed in different formats despite them both coming from a Get-Date call. For example, the end time
gets printed as
"08/19/2020 08:54:51"
and the start time
as
"Mittwoch, 19. August 2020 08:54:08"
(german format). This only seems to happen when I run the script for the first time because as soon as I run it again, the error no longer occurs. What I don't understand is: After checking both the start and the end time, the start time was (as expected) a DateTime object but the end time was just a string, despite both values coming from a Get-Date call. Why does this even happen to begin with and how can I avoid running into this problem (or similar problems)?