0

I want to calculate the difference between two time stamp no matter even it is second, here below is my code snippet:

#Start Timer
$Start_Timer = (Get-Date).DateTime
Write-Host "Start Timer is ---> $Start_Timer"
#End Timer
$End_Timer = (Get-Date).DateTime
Write-Host "End Timer is ---> $End_Timer"
$Current_Time_End = (Get-Date).DateTime
$TotalExecutionTime = $End_Timer - $Start_Timer

Output of the above code is:

Start Timer is ---> Monday, August 13, 2018 6:21:18 PM
End Timer is ---> Monday, August 13, 2018 6:22:55 PM

Error generated

Cannot convert value "Monday, August 13, 2018 6:22:55 PM" to type
"System.Int32". Error: "Input string was not in a correct format."
At D:\Eclipse_Repository\self_repo\jmallick\FileMover.ps1:55 char:1
+ $TotalExecutionTime = $End_Timer - $Start_Timer
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger

What I am doing wrong here?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Jyoti Prakash Mallick
  • 2,119
  • 3
  • 21
  • 38

4 Answers4

2

(Get-Date).DateTime is a string so you cannot do mathematical operations. You can verify this with (Get-Date).DateTime.gettype().fullname.

Using subtraction on the pure date objects e.g. $beforeTime = Get-Date will be what you want to do. This will also return TimeSpan objects

(get-date) - ((get-date).addhours(-1))

Also read this relevant post about calculating execution time in .Net and using StopWatch in PowerShell

Matt
  • 45,022
  • 8
  • 78
  • 119
2

I use this

$t1 = (get-date)
$t2 = (get-date)
$tdiff = $t2-$t1

Output variable example:

$tdiff
$tdiff.minutes
$tdiff.hours

etc

ahmoreish
  • 180
  • 3
  • 8
1

I recommend using [StopWatch] for performance measurement. See following example:

$timer = [System.Diagnostics.Stopwatch]::StartNew()
#do your job
$timer.Stop()

#get timespan
$timer.Elapsed
Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
0

Use this: New-TimeSpan -Start $Start_Timer -End $TotalExecutionTime You'll have time difference expressed in multiple increments (days, seconds etc).

AdamL
  • 12,421
  • 5
  • 50
  • 74