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"

2014-03-28_14-50-59.png

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

2014-03-28_14-30-45.png

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:

2014-03-28_14-38-16.png

At this point $i contains the following value:

1$i

2014-03-28_14-41-48.png

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"

2014-03-28_14-43-41.png

Enclosing the command in dollar sign parenthesis resolves the issue:

1"$(($i=New-TimeSpan -End 2014-04-28T09:00-07).days)"

2014-03-28_14-47-47.png

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"

2014-03-28_14-24-56.png

µ