Powershell: Using variable members in a string
Recently I decided to list my community contributions so if anybody, for whatever reason, was interested I would have everything collected in one place. I pulled some data from my blog, and an excel sheet I had, as well as my MVP page (lists contributions up until 2015) and inserted it in a database.
Then it was time to work with the data.
PowerShell can be a bit funny if you haven’t worked much with variable expansion and scripting before. Usually you can expand/inject a variable in a double quoted string like so:
$name = “Iris”
" $name “
And it would print
Iris
But if the variable is an object that has members you want to access this
$person = @
$Person.Name=“Iris”
” $person.Name"
Will print:
System.Collections.Hashtable.Name
Not quite what you expected. To get the value or use the member you need to wrap the subexpression in parenthesis started with a dollar sign like below
"$($person.Name)"
Which yields:
Iris
So my query looked like this (pardon fugly oneliner- I like to challenge myself to see how compact I can make a line hah!):
For a small snippet that shows the dollar embraced subexpression:
" href=’$($_.Url)’ “
And ze line(s) in full:
Invoke-Sqlcmd -ServerInstance $localInstance $query | % { "<div>$([DateTime]::Parse($_.Date).ToShortDateString()) <a href='$($_.Url)'>$($_.Title)</a> <span class='contribType'>$($_.ContributionType)</span></div>" }
Comments
Thank you so much for the kind words! I like your attitude, and I fully agree. I actually have a few videos planned and as soon as I've unpacked (I just moved to a new apartment) I'm going to record them. I Actually considered using a livestream at https://www.livecoding.tv/livestreams/ once in a while. Any suggestions for videos? The ones I've got planned are on new features in VS 2017.
Last modified on 2016-11-14