Using script blocks within doubled quoted strings in PowerShell

While working on a script to convert an XML export of a new chat application to EML files for ingestion into my company’s compliance system (A task I’ve been doing a lot of over the past year or so), I came across an interesting use of variable usage in double quoted strings. One I was surprised I didn’t think of earlier.
Part of my script entailed providing options for grabbing various date ranges of the XML chat export from the provided REST API. I decided on the following options:

  • Full Export
  • This Date Forward
  • This Date Only

I normally use write-verbose statements partially as comment based help and a light version of logging for scripts like this. So when a non-full export was specified I wanted a write verbose statement like

Write-Verbose "Building REST URL for a $ExportType export using $ExportStartDate"

While a full export would be

Write-Verbose "Building REST URL for a $ExportType”

So I originally started with the following code

if ($ExportType -ne “Full”) {
Write-Verbose "Building REST URL for a $ExportType export using $ExportStartDate"
}
Else {
Write-Verbose "Building REST URL for a $ExportType export"
}

But then it dawned on me, I’ve done some expressions in double quoted strings before. A simple example would be

Write-host “Yesterday was $((Get-date -Hour 00 -Minute 00 -Second 00).adddays(-1).tostring())"

Could I do something a little more complex? Turns out I can! The following worked and could fit on one line

Write-Verbose "Building REST URL for a $ExportType export $(if($ExportType -ne “Full”) {"using $ExportStartDate"})"

Thinking about it some more. I wondered if I had a more complex statement as a script block. Could I pass that as well? Turns out I can!

[ScriptBlock]$CalculatedValue = {if($ExportType -ne “Full”) {"using $ExportStartDate"}}
Write-host "Building REST URL for a $ExportType export $(& $CaculdateValue)"
Write-host "Building REST URL for a $ExportType export $(Invoke-Command $CaculdateValue)"

Using either the call operator (&) or Invoke-Command I can execute a script block in a double quoted string. A fun trick I hope to use in the future to tighten up some code.

About mell9185

IT proffesional. Tech, video game, anime, and punk aficionado.
This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply