March 19th, 2011

Scripting Wife Uses PowerShell to Get Days Until NCAA Final Four

Summary: The Scripting Wife learns how to use Windows PowerShell to determine the number of days until the NCAA championship game.

Microsoft Scripting Guy, Ed Wilson, here. It has been an extremely exciting week. I finished writing all of the Windows PowerShell 2011 Scripting Games events, and I emailed them to the guest commentators. In addition, I received word that the Scripting Guys will have a booth at TechEd in Atlanta. If that was not enough, Morehead State University (MSU) pulled off a major upset in the NCAA basketball tournament game against the University of Louisville. MSU won in the final second of the game when one of their players sank a three pointer from the top of the key. Facebook was smothered with ecstatic well wishes.

I look up, and it is the Scripting Wife tip toeing across the living room. Her shoes are off, and she makes no noise as she moves. Out of the corner of my eye, I search desperately for an exit because I see that she is carrying her laptop with her. It’s too late, however, because I have been spotted and a hasty departure would raise suspicion and call into question my sincerity in helping the Scripting Wife be competitive in this year’s Scripting Games.

“Good news,” the Scripting Wife said cheerily when she saw that I was not going to run and hide from her laptop.

“Yeah, you are right. Morehead State University beat Louisville in round one of the NCAA tournament,” I said.

“The Beagles,” she asked.

“No. Eagles,” I corrected.

“Whatever. What is important is that the Kentucky Wildcats won. But that is not the good news,” she asserted.

“What could be better than a first round upset by a serious underdog?” I asked.

“The good news is that you get to teach me about dates,” she said as she smiled.

“No problem. I had some great dates when I was in Egypt; they are better than candy,” I deadpanned.

“You are not funny,” she said, “I am holding my laptop why?”

“So what do you want to know about working with dates in Windows PowerShell?” I asked.

“Let’s take your storied Morehead Eagles as an example. If they make it to the NCAA championship game this year, how long do I have to put up with your silly antics?” she asked.

“Oh, so what you want to do is to subtract two dates so you can get the number of days between them,” I said.

“Yes, that is right.”

“Open your Windows PowerShell console; you can do this directly from the Windows PowerShell prompt.”

“Way ahead of you. Just tell me what to type.”

“There are actually several ways of doing this. Let’s start with the longest way, and work our way down from there,” I said.

“Why can’t you ever give me a simple answer to a simple question?” she complained.

“Because I know you are smart, and you would eventually begin to question why things work a certain way. So it is better for me, and for you, to give you the background in addition to the answer,” I said.

“OK. I guess that makes sense.”

“Today is March 19, 2011. The NCAA championship ends on April 4, 2011—the same day that the 2011 Scripting Games begin. Therefore, you will need to create a couple of dates. First, use square brackets around the word DateTime, and then type the April 4 date,” I instructed.

The Scripting Wife turned to the Windows PowerShell console on her computer, and typed the following code at the Windows PowerShell prompt.

[datetime]”4/4/11″

When she pressed ENTER, the following output appeared.

Image of command output

“Wow, that was really exciting,” the Scripting Wife said with heavy sarcastic tones.

“I think so. You just took a string, and turned it into a DateTime object. Because you have a DateTime object, you can actually do some pretty cool things,” I explained. “Use the Get-Member cmdlet to display the members of the object that come back when you type that code.”

The Scripting Wife looked at me for just a second with an expression that seemed to indicate that she thought my head was sprouting daises. Finally, I imagine, she made up her mind, pressed the Up arrow key to recall the previous command, pressed the End key to take her to the end of the command, typed the pipeline character, and then typed Get-Member. The exact command she produced is shown here.

[datetime]”4/4/11″ | Get-Member

The output from that command is shown in the following image.

Image of command output

“OK. So I have a DateTime object. Now what?” she asked impatiently.

“Do you remember the cmdlet that gets the current date?” I asked.

“Sure. It is Get-Date.”

“Use Get-Date to produce the date for today’s date to subtract from the April 4 date.”

After a little bit of clicking, she produced the following code.

[datetime]”4/4/11″ – Get-Date

“It doesn’t work,” she said as she turned the screen on her laptop to show me the error message that is shown in the following image. “And don’t tell me it is not bogus.”

Image of error message

“I will admit it is not the most instructive. But notice that it says something about a dash (-). That means it sees the minus as a parameter. You need to put parentheses around your Get-Date cmdlet,” I said.

She typed for less than a second and produced the command and the associated output that is shown here.

PS C:\> [datetime]”4/4/11″ – (Get-Date)

 

Days              : 16

Hours             : 0

Minutes           : 0

Seconds           : 0

Milliseconds      : 0

Ticks             : 13824000000000

TotalDays         : 16

TotalHours        : 384

TotalMinutes      : 23040

TotalSeconds      : 1382400

TotalMilliseconds : 1382400000

 

PS C:\>

“Well that is pretty cool,” she admitted.

“Wait until I show you the next cool thing. Use the Up arrow, to retrieve your previous command and pipe the results to Get-Member. You can use the GM alias if you wish,” I said.

“OK,” she said, and she turned the monitor towards me displaying this output.

PS C:\> [datetime]”4/4/11″ – (Get-Date) | gm

 

 

   TypeName: System.TimeSpan

 

Name              MemberType Definition

—-              ———- ———-

Add               Method     System.TimeSpan Add(System.TimeSpan ts)

CompareTo         Method     int CompareTo(System.Object value), int CompareTo(System.TimeSpan v..

Duration          Method     System.TimeSpan Duration()

Equals            Method     bool Equals(System.Object value), bool Equals(System.TimeSpan obj)

GetHashCode       Method     int GetHashCode()

GetType           Method     type GetType()

Negate            Method     System.TimeSpan Negate()

Subtract          Method     System.TimeSpan Subtract(System.TimeSpan ts)

ToString          Method     string ToString()

Days              Property   System.Int32 Days {get;}

Hours             Property   System.Int32 Hours {get;}

Milliseconds      Property   System.Int32 Milliseconds {get;}

Minutes           Property   System.Int32 Minutes {get;}

Seconds           Property   System.Int32 Seconds {get;}

Ticks             Property   System.Int64 Ticks {get;}

TotalDays         Property   System.Double TotalDays {get;}

TotalHours        Property   System.Double TotalHours {get;}

TotalMilliseconds Property   System.Double TotalMilliseconds {get;}

TotalMinutes      Property   System.Double TotalMinutes {get;}

TotalSeconds      Property   System.Double TotalSeconds {get;}

“What kind of object is it?” I asked her.

“It is a TimeSpan object. I can read you know,” she chastised.

“I know. Now, is there a cmdlet that has the word TimeSpan in it?” I asked.

The Scripting Wife quickly typed Get-Command *Timespan and produced the output shown here.

PS C:\> Get-Command *timespan

 

CommandType     Name                                      Definition

———–     —-                                      ———-

Cmdlet          New-TimeSpan                              New-TimeSpan [[-Start] <DateTime>] [[-…

“There is a New-TimeSpan cmdlet,” she said triumphantly.

“Now use the start and the end parameters to figure out the time span between todays date and the day of the NCAA championship game,” I said.

“Let’s see, you said the NCAA championship game is the same day the 2011 Scripting Games kick off. That means it is April the 4th, 2011. I think I can figure this out,” she said with confidence.

She typed New-TimeSpan -Start 3/19/11 -End 4/4/11. The actual keystrokes that she typed are shown here.

New-t<tab><space>-s<tab><space>3/19/11<space>-e<tab><space>4/4/11<enter>

When she pressed ENTER, the output shown here appeared.

Image of command output

“That is easy,” she said. “So I only have to put up with you for 16 more days, assuming Morehead State can pull off the upset of the century.”

“Millennium,” I corrected.

“Huh?”

“Millennium,” I said. “The century is only 11 years old. You need more history to properly characterize Morehead State University’s chances. But it is a nice thought.”

“You always pull for the underdog, don’t you?” she said.

“I can’t help it. I am sentimental. Last year I cheered for Winthrop University,” I said.

“You might be sentimental, but you are also a script monkey. I will be back with more questions later,” she said as she departed making much more noise than when she entered. In fact, it sort of sounded like a Dr. Evil laugh…”bwaaa haaaaaa haaaaa…”

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Author

0 comments

Discussion are closed.