Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse the contents of a string on-the-fly in PowerShell [duplicate]

The first example below is a normal static string getting parsed. The second example is me attempting to do the same thing but get the string to parse live, dynamically. I need to know what to put in the place of (($myparse gets evaluated)) below in order to get it to parse the contents of $myparse on-the-fly. I'm sure it's some kind of script block, but I can't figure out what kind.

The following code correctly parses the static string as "Hello John Smith" and stores it in $mysalutation:

>$firstName = "John"
>$lastName = "Smith"
>$mysalutation = "Hello $firstName$(if($lastname) {" " + $lastName})."
>$mysalutation
Hello John Smith.

What I want to do is parse the same string on the fly:

>$myparse = 'Hello $firstName$(if($lastname) {" " + $lastName}).'
>$myparse
Hello $firstName$(if($lastname) {" " + $lastName}).

>$firstName = "Jason"
>$lastName = "Bourne"
>$mysalutation = (($myparse gets evaluated))
>$mysalutation
Hello Jason Bourne.
like image 566
user8017794 Avatar asked Feb 01 '26 00:02

user8017794


1 Answers

You are looking for the ExpandString function:

$ExecutionContext.InvokeCommand.ExpandString($myparse)
like image 109
Martin Brandl Avatar answered Feb 03 '26 14:02

Martin Brandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!