Share via


The parsing mystery of my HERE-STRING

I was helping a friend re-write a script to make it visually more appealing.   For some scenarios I LOVE using Here-Strings.

If you've never encountered one a Here-String looks like this

$Somedata=@'
Here is something I am writing
This is what it will look like at the end
Isn't this cool?
'@

And literally it will output to the scene just the way it looks.   Like this.

I like to think of them as "Here, this is what it will look like String"

Another form of Here-String uses double quotes.   This allows the internal content to be evaluated and parsed which means you can plug in variables.   It's a bit slower because you are parsing the content but allows you to neat things, like a simple form letter when welcoming an Employee

$Welcome=@"
Hello $FirstName $LastName and welcome to Contoso!

Your login ID is $LoginID

Your Temporary password is $SecretPassword
"@

Here's what that might look like.

But here is where I ran into a problem.   I can also do THIS in a Here-String.

$Stuff=@"
$($FirstName.Substring(0,4)) is the first Four letters of your First Name.
"@

So when you see $() in a String it's say "Run this code and the output of this will be injected into the string...."

This works fine if the output is a pure string.   But what if you have some really cool stuff like Event logs,  content from Active Directory or anything that's output is a pinch more than a String.

Initially if you do this.

$Output=@"
Woohoo!  Check out my cool event logs!
$(Get-EventLog -logname System -newest 15)
"

You end up with this mess.

That's because a Here-String (just like a regular String object) can ONLY deal with "String" data and this is a .NET Object that was produced by Get-EventLog.

So you just need to help it all.   You can (in most cases!) Convert that into something perfectly useful by piping the results into an OUT-String Cmdlet.

$Output=@"
Woohoo!  Check out my cool event logs!
$(Get-EventLog -logname System -newest 15| Out-String)
"

Now you'll get something much more useful like below!

This is not just isolated to Here-Strings but regular strings as well.   But the same trick works both ways.  Neat eh?

Just a little something fun I thought I'd share out today!

Cheers all and remember, the Power of Shell is in YOU!

Sean
the EnergizedTech, Microsoft PFE