3

I have a scenario where I need to construct a powershell path as $RemotePath = '$($env:USERPROFILE)\Desktop\Shell.lnk'. This variable gets passed to a remote machine where it needs to be executed. The remote machine receives this as a string variable. How do I expand the string to evaluate $env:USERPROFILE?

Rohit Mitra
  • 162
  • 4
  • 13

2 Answers2

5

Expand the string on the remote side:

$ExecutionContext.InvokeCommand.ExpandString($RemotePath)
Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Be aware that like `Invoke-Expression` and `[ScriptBlock]::Create()`, `$ExecutionContext.InvokeCommand.ExpandString` could be exploit using malicious code injections, see: [Rule for the use of the command: [ScriptBlock]::Create](https://github.com/PowerShell/PSScriptAnalyzer/issues/1454) – iRon May 10 '20 at 14:57
1

By using a double quotes. PowerShell won't expand variables inside single-quoted strings.

ojk
  • 2,502
  • 15
  • 17
  • 1
    When using double quotes the variable is expanded on the local side, not on the remote side as the OP wants. – Ansgar Wiechers Dec 01 '14 at 11:32
  • I see. Thanks for the correct answer, and the explanation :) – ojk Dec 01 '14 at 11:34
  • 1
    Yup. As Ansgar mentioned, my requirement is to evaluate the expression on the remote machine, since I want the UserProfile value from the remote machine. – Rohit Mitra Dec 01 '14 at 11:48