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?
Add a comment
|
2 Answers
Expand the string on the remote side:
$ExecutionContext.InvokeCommand.ExpandString($RemotePath)
1 Comment
iRon
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)By using a double quotes. PowerShell won't expand variables inside single-quoted strings.
3 Comments
Ansgar Wiechers
When using double quotes the variable is expanded on the local side, not on the remote side as the OP wants.
ojk
I see. Thanks for the correct answer, and the explanation :)
Rohit Mitra
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.