Over the last few weeks I've read about other people's PowerShell prompts and offered a few suggestions of my own. This week's Friday Fun creates colorful holiday prompt that counts down the number of days until Christmas.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
The function, uses a simple timespan object as part of the prompt. The fun part is that I use the foregroundcolor parameter of Write-Host to add a little whimsy. Here's what the code looks like.
[cc lang="PowerShell"]
Function Prompt {
$time=([datetime]'12/25/2011'-(get-date)).ToString().Substring(0,11)
$text="[**Christmas in $($time)**]"
$text.tocharArray() |foreach {
if ((Get-Random -min 1 -max 10) -gt 5) {
$color="RED"
}
else {
$color="GREEN"
}
write-host $_ -nonewline -foregroundcolor $color
}
Write (" PS " + (Get-Location) + "> ")
} #end function
[/cc]
I cast the string '12/25/2011' as a datetime object and subtract the current datetime. PowerShell writes a timespan object to the pipeline which has a ToString() method. By itself I get a result like 34.05:25:44.4032824. But I don't really care for the millisecond part so I use the String object's SubString() method to parse it. I could have used a few lines to do this but threw it all in a one line command. The result becomes part of my text.
The fun part is that I turn the text into an array and pipe each letter to ForEach-Object. Within the loop I get a random number between 1 and 10. If the number is greater than 5 then I write the character to the screen in Red, otherwise in Green. This is my version of a coin toss. I tried getting random numbers between 0 and 1 but I didn't seem to get enough variation. In my testing, this works fine. The last part of the prompt is the standard PS and current location. But of course, you could put in anything you want.
Here's a sample of the finished function.
I doubt this will rock your world but maybe it will make you smile.
Download ChristmasPrompt.ps1
Fun! Here’s a Chanukah version for 2011.
Function Prompt {
$time=([datetime]’12/20/2011 18:00′-(get-date)).ToString().Substring(0,11)
$text=”[**Chanukah in $($time)**]”
$text.tocharArray() |foreach {
if ((Get-Random -min 1 -max 10) -gt 5) {
$color=”Yellow”
}
else {
$color=”GREEN”
}
write-host $_ -nonewline -foregroundcolor $color
}
Write (” PS ” + (Get-Location) + “> “)
} #end function
Thank you. I love it.
Awesome. I added this to my profile immediately. 🙂