January 8th, 2007

Two plus two equals "Monday" ?

PowerShell Team
PowerShell Team

In PowerShell, two plus two does not always equal four. 

Why?  Because there are twos and there are twos.

Let me explain.  PowerShell does a ton of work on your behalf so you can think about what you want to do and not how to do it.  Think about the difference between an automatic transmission and a manual one.  An automatic does a ton of work on your behalf but sometimes it doesn’t have the information to make the right decision.  That is why automatic transmissions allow you to shift into 1, 2 ,3  or D (which automatically shifts for you).  Occassionally, you need to override the decision making.  In the end, an automatic transmission is a pretty good deal. 

PowerShell is actually more like a tiptronic transmission (which is what I drive) which gives you the option of being automatic or manual giving you the best of both worlds..  Most people don’t have experience with those so I’ll just go with the automatic analogy. 

So back to two plus two.  Sometimes two is a string and sometimes it is an int.  So, to steal a little from Tolstoy – when then must we do? 

What PowerShell does is to use the type of the first element of the expression to type the expression.  If it is an number the addition is a numeric addition.  If it is a String, the addition is a string addition.  Ditto for multiplication.  Let me show you:

PS> 2+2
4
PS> 2+”2″
4
PS> “2”+”2″
22
PS> “2”+2
22
PS> 2 * 30
60
PS> “2” * 30
222222222222222222222222222222
PS> [Int]”2″ + 2

PS> [INT](“2” + 2)
22
PS> [STRING]2 + 2
22
PS> [INT]$x = “2”
PS> $x + 2
4

 

Got your head around that one yet?  Try this one:

 

PS> [timespan]2 + 2

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 4
TotalDays         : 4.62962962962963E-12
TotalHours        : 1.11111111111111E-10
TotalMinutes      : 6.66666666666667E-09
TotalSeconds      : 4E-07
TotalMilliseconds : 0.0004

PS> [DateTime]2 + 2

Monday, January 01, 0001 12:00:00 AM

 

I LOVE this stuff! 

Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Category
PowerShell

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.