Search code examples
powershelllocalremote-desktop

How do I access a local directory inside Invoke-Command?


I have some files and a script that I run in an elevated session on someone's desktop, and I do it because there are multiple steps involving copying folders into protected areas and messing with the registry. To accomplish this, I use Invoke-Command. The credentials I provide allow me to do so, but I have encountered an issue.

The script is in the same folder as files I want to copy. When I get that script's location, it gives me the wrong directory.

I want c:\Users\TheLocalUser\Files, but instead, I get c:\Users\TheCredentialsIProvided\Files.

Because of this, my script cannot technically find the files I wish to copy. How do I reference these files stored on someone's computer using my script's location?

If that isn't possible, is there a better method out there?


Solution

  • Don't use arbitrary directories in user directories but rather have a centralized location for your script. If you need to find the user directory let script ask for the username if you can't design a process that allows for execution from within the user context. For instance, as you are running Invoke-Command with credentials, you could let the user start the script which would mean the home of the user would be what you expect.