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?

2 Answers 2

5

Expand the string on the remote side:

$ExecutionContext.InvokeCommand.ExpandString($RemotePath)
Sign up to request clarification or add additional context in comments.

1 Comment

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](github.com/PowerShell/PSScriptAnalyzer/issues/1454)
1

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

3 Comments

When using double quotes the variable is expanded on the local side, not on the remote side as the OP wants.
I see. Thanks for the correct answer, and the explanation :)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.