4.4. Invoking Strings as Expressions

Almost all script languages have a special function or operation that takes a string as an input parameter, compiles it, and executes it as a piece of code. Other popular languages such as JavaScript call that function eval. PowerShell's equivalent is the Invoke-Expression cmdlet. Strings can be either passed as parameters or piped in from another command. Here is how to execute a simple string like "Write-Host ‘invoked expression'":

PS> Invoke-Expression "Write-Host 'invoked expression'"
invoked expression

Note that we have to escape quotes or use single quotes inside the string that gets executed. This is quite cumbersome, but it is worth the effort. We can manipulate strings at runtime and create highly ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.