Windows Tip Sheet
Back In Time
The date/time prompt, this time with PowerShell.
- By Jeffery Hicks
- 03/07/2007
Last week, I showed how to customize your CMD prompt to display the current date and time. Let's do it again, this time with a PowerShell prompt. My prompt looks like this:
1/17/2007 9:23:41 AM PS C:\ >
And it's colored yellow. I define a function called Prompt in my PowerShell profile that looks like this:
function prompt
{
$myPrompt=(get-date).ToShortDateString() + " " + '
(get-date).ToLongTimeString()+ " PS " + $(get-location) + " >"
Write-Host ($myPrompt) -nonewline -foregroundcolor Yellow
return " "
}
There is a default prompt function in the All Users profile, but since my personal profile gets applied second, it "wins."
The function creates a variable called $myPrompt that's created by concatenating the results of several cmdlets. The date component is created with this:
(get-date).ToShortDateString()
and the time component is created with this:
(get-date).ToLongTimeString()
Tech Help—Just An
E-Mail Away |
Got a Windows, Exchange or virtualization question
or need troubleshooting help? Or maybe you want a better
explanation than provided in the manuals? Describe
your dilemma in an e-mail to the MCPmag.com editors
at [email protected];
the best questions get answered in this column and garner
the questioner with a nifty Redmond T-shirt.
When you send your questions, please include your
full first and last name, location, certifications (if
any) with your message. (If you prefer to remain anonymous,
specify this in your message, but submit the requested
information for verification purposes.) |
|
|
In both cases I take the result of the Get-Date cmdlet, which is why it is enclosed in parentheses, and then I invoke an appropriate method to get short versions of the date and time respectively. (I could have displayed the day of the week, but it's not abbreviated and I didn't want to take up more screen space with a longer prompt.)
The rest of the prompt is the standard PS plus current location and the > symbol.
I get the yellow color by calling Write-Host and adding the –foregroundcolor switch. This makes my prompt stand out from the rest of the console.
Now, no matter what shell I'm in, I can see at a glance what time it is and how much longer I have to work!
About the Author
Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.