PowerShell Time Multiplication

PowerShell Time Multiplication

Hello,

PowerShell is a great tool for date and time manipulation. I will show you a few example about how to use PowerShell to addition/subtract TimeSpan to DataTime object, and how to multiply TimeSpan.

PowerShell Time Multiplication – Addition

(New-TimeSpan -Hours 3) + (New-TimeSpan -Hours 3)
PowerShell Time Multiplication - Addition

Addition

PowerShell Time Multiplication – Subtract TimeSpan to DateTime

You can add TimeSpan seamlessly, and then use it with DateTime objects to compare dates, or calculate date with a TimeSpan subtraction/addition :

(Get-Date) - ((New-TimeSpan -Hours 3) + (New-TimeSpan -Hours 3))
PowerShell Time Multiplication - TimeSpan Addition

Remove TimeSpan Addition to a DateTime

PowerShell Time Multiplication – Multiplication

Addition and subtraction is nice, but what about multiplication ? Indeed, you may want to multiply TimeSpan before adding them to a DateTime Let’s try it :

(New-TimeSpan -Hours 3) * 2
PowerShell Time Multiplication - Multiplication Error

Multiplication Error

Method invocation failed because [System.TimeSpan] does not contain a method named ‘op_Multiply’.
At line:1 char:1
+ (New-TimeSpan -Hours 3) * 2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (op_Multiply:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound

As you can read, this does not work,there is no multiply method on a TimeSpan object :

PowerShell Time Multiplication - Get-Member

Get-Member

but you can trick cheat :

1..4 | % -Begin {$Total = 0} -Process {$Total += (New-TimeSpan -Hours 3)} -End {$Total}
PowerShell Time Multiplication - Multiplication

Multiplication

Et voilà, you can multiply TimeSpan objects even if the objects don’t have the “Multiply” method !

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.