7Apr/110
Object Property Expansion in Strings
Just a quick on really. Ever had a problem where you had a property of an object that was a string that you wanted to use in another string?
For example, if you had a variable that looked like this:
$Name = "Posh Pete"
You could expand that really easily in another string:
write-host "Hi, my name is $Name"
Which returns "Hi, my name is Posh Pete" which is great.
However, say you had an object that had 2 properties, "FirstName" and "LastName"
#Quick and dirty object creation $NameObject = "" | Select FirstName,LastName $NameObject.FirstName = "Posh" $NameObject.LastName = "Pete"
Now, say you wanted to do what we did before:
write-host "Hi, my name is $NameObject.FirstName $NameObject.LastName"
You get a rather nasty looking response:
Hi, my name is @{FirstName=Posh; LastName=Pete}.FirstName @{FirstName=Posh; LastName=Pete}.LastName
Eeeeek!
So, to get around this, all you need to do is wrap your expressions in a $(), so it looks like this:
write-host "Hi, my name is $($NameObject.FirstName) $($NameObject.LastName)"
Job done



