Thursday, June 4, 2015

#80 : Find difference in two dates with Powershell?

Sometimes we need to get this information like total time taken by script or total time a program ran. This is quite simple to get the difference between two dates if the data type is set to DateTime.

Below is a sample script for the same :
This script will show the difference in Seconds, Hours and Minutes. You can also go to even deeper such as milliseconds.

Function Get-DateDifference( [DateTime]$FromDate, [DateTime] $ToDate , [String]$OutputType ) 
{
 [int]$Output=-1
 
 if ( $FromDate -gt $ToDate ) 
 {
  echo "Error: [From date] should not be greater than [To Date]."
 }
 else 
 {
  Switch ( $OutputType )
  {
   "Seconds"  {  $Output=$($ToDate - $FromDate).TotalSeconds } 
   "Hours"  {  $Output=$($ToDate - $FromDate).TotalHours } 
   "Minutes"  {  $Output=$($ToDate - $FromDate).TotalMinutes } 
   
  }
  
  if ( $Output -ne -1 ) 
  {
   echo "$Output $OutputType"
  }
 }
}

$Date1=Read-Host "Enter the From Date"
$Date2=Read-Host "Enter the To Date"

Get-DateDifference -FromDate $Date1 -ToDate $Date2 -OutputType 'Seconds'


Hope this was helpful tip.
Enjoy learning Powershell!

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...