Iris Classon
Iris Classon - In Love with Code

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

Leave a comment below, or by email.
Rudenco Victor
11/16/2016 2:24:01 AM
Hi Iris, probably a lot of work, would like to see more of your videos on youtube. Charismatic  and really inspirational with your activity and sharing your ideas . I think everybody should be positive and tend to know more , make step further in their carreers and learn to manage data, do things faster with ease and optimistic attitude. It's wonderful when you do what you like and you see your resut, no matter what obstacles you have. 

Liked your story with starting coding.

Regards 
Iris Classon
11/19/2016 8:47:25 AM
Reply to: Rudenco Victor
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

comments powered by Disqus