How to elevate a Powershell script from within a script
07:31 13 Feb 2020

I'm new to Powershell, but in a lot of ways liking it a lot. For reasons, I have created a script that loads a set of local admin credentials from a file on the hard drive and creates a PSCredential-object, $MyCred.

I want to use $MyCred to elevate a separate script (which makes a few registry changes to open RDP connections). I've tried passing the $MyCred to the Start-Process cmdlet:

Start-Process Powershell.exe -Credential $MyCredential

Then I receive the following error:

Start-Process : This command cannot be run due to the error: The directory name is invalid.

If I run the Start-Process with -credential and an empty variable, I'm prompted for username and password. When I type them in, I get an elevated powershell prompt with no issues and am able to make the changes in registry to my test system.

I've verified the contents of $myCred and it has both U/N and P/W stored correctly (as in, identical to what I input manually). Using New-PSSEssion like

New-PSSession -Credential $MyCredential

returns access denied, which I've read is also disabled by default on a lot of systems.

In an ideal world, the code would look something like:

Start-Process Powershell.exe -Credential $MyCredential -File C:\MyScript.ps1

This should start an elevated powershell that runs a few commands in the second script and then terminates. What am I missing here?

Grateful for all help I can get, thanks! I might be something completely obvious.


Background is, we have some computers that we cannot ourselves get our hands on, and are also not able to reach through RDP. We do have users at the sites that can run the script for us. But it's important that they do not get the local admin-password. So we want to create a script that reads an encrypted password file, generates the local admin PSCredential object, and passes that to a script that makes the necessary registry changes to allow for RDP access.

powershell