Nov 142016
 
 November 14, 2016  Posted by at 1:21 pm PowerShell, Uncategorized  Add comments

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.

community-contributions

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>"
 
}

  2 Responses to “Powershell: Using variable members in a string”

  1. 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

    • 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.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

What is 8 + 14 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)