0

I want to substitute a variable to existing string, say:

$x = "Hello `$xxx friend"
$xxx = 777
similar_to_js_exec($x) # i need here "Hello 777 friend"

How can i do it ?

Oleg Skripnyak
  • 301
  • 2
  • 13
  • depending on your situation, you may find alternate concepts worth while. take a look at the `-f` string format operator and the `here-string` construct. the `Invoke-Expression` cmdlet is considered highly risky [similar to sql injection] AND is so often used in malware that it is often entirely blocked. – Lee_Dailey May 17 '20 at 03:03
  • I've used $url = Invoke-Expression ("""" + $_["ConnectionUri"].Value + """"), ugly :) Actually there no user input, only hardcoded, so no injection.This is an Exchange endpoint depending of Azure envrionment, CN, DE, GOV, so had to pass an URL with parameter which has another parameter ie."https://outlook.office365.com/PowerShell-LiveId?BasicAuthToOAuthConversion=$UseTokenAuth". But thank you for the help ! – Oleg Skripnyak May 17 '20 at 04:16
  • ah! thank you for the added info. [*grin*] ///// please, take a look at the `-f` operator. it _usually_ makes that nasty nested set of quotes entirely unneeded. – Lee_Dailey May 17 '20 at 04:28
  • @Lee_Dailey nice feature, this is the same as .NET String.Format(), of course i can use it, but already have used the code above, and it faster than just String.Format(), but thanks for your suggestion ! – Oleg Skripnyak May 17 '20 at 05:49
  • Does this answer your question? [Expand string Variable stored via Single Quote in Powershell](https://stackoverflow.com/questions/27226606/expand-string-variable-stored-via-single-quote-in-powershell): `$ExecutionContext.InvokeCommand.ExpandString($x)` – iRon May 17 '20 at 06:23
  • @iRon Yes, it's worked (with $UseTokenAuth locally defined) - PS: $ExecutionContext.InvokeCommand.ExpandString("https://outlook.office365.cn/PowerShell-LiveId?BasicAuthToOAuthConversion=`$UseTokenAuth"), make it as answer – Oleg Skripnyak May 17 '20 at 06:53
  • 1
    @OlegSkripnyak - i see that you got your actual problem solved ... good to know! [*grin*] – Lee_Dailey May 17 '20 at 09:00

1 Answers1

1

You need to use Invoke-Expression

$x = '"Hello $xxx friend"'
$xxx = 777
Invoke-Expression $x
Carlos Garcia
  • 2,771
  • 1
  • 17
  • 32
  • I am running it locally and it works, what error are you getting? – Carlos Garcia May 17 '20 at 01:35
  • @OlegSkripnyak make sure you are using the quotes as I use them. Invoke-Expression will take whatever is in the string and execute it, so you need first single quotes `'` and then double quotes `"` – Carlos Garcia May 17 '20 at 01:38
  • 1
    Your variant is good working, just have to embed my var into single quotes, thank you – Oleg Skripnyak May 17 '20 at 01:38
  • Had to change it to some wonderful construction, where $_ is .NET Dictionary PS: $url = Invoke-Expression ("""" + $_["ConnectionUri"].Value + """") – Oleg Skripnyak May 17 '20 at 06:02