PowerShell: Output the Result of a Command and Assign it to a Variable in One Line
As of today, there is one month left until the PowerShell Summit North America 2014. I tweeted something out last night and thought I would write a quick blog about it since I often find myself looking for a tweet months later when I can't remember how I did something that I previously tweeted out.
This tweet used all 140 characters that twitter allows:
1"There are $(($i=New-TimeSpan -End 2014-04-28T09:00-07).Days) days & $($i.Hours) hours left until the #PowerShell Summit North America 2014"
This portion of the command is assigned to a variable named $i
(technically it's assigned to a
variable named i
):
1New-TimeSpan -End 2014-04-28T09:00-07
It determines the amount of time until 9am on April 28, 2014 in the GMT -7 timezone (the current timezone for Seattle) so you can run this command from any time zone and it will display accurate information.
Here I've assigned the value to the variable $i and displayed the value of the days property, all in one line:
At this point $i
contains the following value:
1$i
When you surround it by quotation marks you end up with a hot mess:
1"($i=New-TimeSpan -End 2014-04-28T09:00-07).days"
Enclosing the command in dollar sign parenthesis resolves the issue:
1"$(($i=New-TimeSpan -End 2014-04-28T09:00-07).days)"
Now you can use the $i
variable on the same line to display the hours in addition to the days since
you wouldn't want to show up to the PowerShell Summit too many hours early:
1Write-Output "There are $(($i=New-TimeSpan -End 2014-04-28T09:00-07).Days) days & $($i.Hours) hours left until the #PowerShell Summit North America 2014"
µ