O'Reilly logo

Pro Windows PowerShell by Hristo Deshev

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required