Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find time difference in minutes using a PowerShell script

I am trying to find the time difference between the last updated time and current time for a file. How do I extract TotalMinutes data from the output?

$Date = Get-Date
$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
    $FileDate = $File.LastWriteTime
}
$DURATION=$Date-$FileDate
Echo $DURATION

Output is coming as below
Days              : 0
Hours             : 2
Minutes           : 21
Seconds           : 37
Milliseconds      : 311
Ticks             : 84973115857
TotalDays         : 0.0983485137233796
TotalHours        : 2.36036432936111
TotalMinutes      : 141.621859761667
TotalSeconds      : 8497.3115857
TotalMilliseconds : 8497311.5857
like image 712
surendra Avatar asked May 30 '16 09:05

surendra


People also ask

How does PowerShell calculate time?

Using the Get-Date Command The number one command to consider when working with dates and times in PowerShell is the Get-Date command. By running Get-Date just by itself, you will output a DateTime object with the current date and time. Using the Get-Member command, we can see that the output is a System.

How do I use TimeSpan in PowerShell?

The New-TimeSpan cmdlet creates a TimeSpan object that represents a time interval. You can use a TimeSpan object to add or subtract time from DateTime objects. Without parameters, a New-TimeSpan command returns a TimeSpan object that represents a time interval of zero.


3 Answers

You will not need a loop, after getting a single file:

$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
    $FileDate = $File.LastWriteTime
}

In this case, $Files might as well be $File, making the loop completely redundant:

$File = gci "C:\Users\ABCD\Documents\command.txt"
$FileDate = $File.LastWriteTime

In the exact same way you extracted LastWriteTime, you can get TotalMinutes:

$Date = Get-Date
$DURATION = $Date - $FileDate
$DURATION.TotalMinutes
like image 65
xXhRQ8sD2L7Z Avatar answered Oct 12 '22 22:10

xXhRQ8sD2L7Z


Here is a complete answer:

$Date = Get-Date
$Files = gci "C:\Users\ABCD\Documents\command.txt"
ForEach ($File in $Files){
    $FileDate = $File.LastWriteTime
}
$DURATION=$Date-$FileDate
Write-Host "$($DURATION.TotalMinutes)"
like image 28
TravisEz13 Avatar answered Oct 12 '22 22:10

TravisEz13


You can use the below command to get just TotalMinutes

$mins = $DURATION.TotalMinutes
like image 28
user14631926 Avatar answered Oct 12 '22 22:10

user14631926