Script run as and registry access denied

I’m trying to run a script in automation, with “Run As”-credentials that fails when attempting to create a registry key in the HKCU-hive:

Access to the registry key 'HKEY_CURRENT_USER\Software\Some\Registry\Key' is denied

The cause is likely that the process is being run without the user profile (equivalent of runas /noprofile …) which means the registry hive isn’t being loaded.

Is it possible to have loading of the user profile as a toggle for ‘Run As’ in a future version?

A repro-script is trivial but here it is anyway :slight_smile:

New-Item 'HKCU:\Software\Some\Registry\Key' -Force

Product: PowerShell Universal
Version: 3.1.4

We’ll we don’t have it in the UI, there is actually a -LoadProfile parameter to New-PSUScript. You could try that to see if it fixes it.

1 Like

Indeed it does :slight_smile:

Hopefully an option will come to the UI as well :+1:

Looks like it was a false positive, specifying -LoadProfile stopped working after the server was rebooted, my theory, through testing with runas.exe is that the userprofile stays around for a bit if it has been loaded earlier.

I now have something like this:
New-PSUScript -Name "MyScript.ps1" -Path "MyScript.ps1" -Environment "7.2.5" -MaxHistory 30 -Credential "MyUser" -LoadProfile


If (-not (Test-Path ‘HKCU:\Software\Some\Registry\Key’ -ErrorAction Continue)) {
New-Item ‘HKCU:\Software\Some\Registry\Key’ -Force

Error is the same as reported earlier [error] Access to the registry key 'HKEY_CURRENT_USER\Software\Some\Registry\Key' is denied.

When -LoadProfile is specified, what happens in the code? I see ProcessStartInfo has the LoadUserProfile property which probably needs to be set to true?

Hmmm that’s the property we are setting. I wonder if we need to do something else to get the hive to mount.

            var startInfo = new ProcessStartInfo();
            startInfo.FileName = powerShellPath;
            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;
            startInfo.Arguments = commandLine;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                startInfo.LoadUserProfile = loadProfile;

Well the documentation I link state that LoadUserProfile is only used if Domain, Username, Password is set on the ProcessStartInfo object, so maybe it’s being ignored, but then how is the script being run as a different user?

Any idea as to what else I could do to help get to the bottom of this?

I’ll raise an issue for this. I don’t know why this isn’t happening. We are setting the credentials on the ProcessStartInfo object in order to run the job as another user.