10

I need to permanently add a scripts folder to my PowerShell path (not just a particular session). I am running the following code:

[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\scripts", "Machine")

The error is as follows:

Exception calling "SetEnvironmentVariable" with "3" argument(s): "Requested registry access is not allowed."

How do I get registry access/fix this?

EDIT: Not sure if it helps, but I'm using PowerCLI (VMware PowerShell API) on Windows Server 2012.

corneria
  • 608
  • 3
  • 11
  • 24

4 Answers4

14

It sounds like you might not be running as an elevated admin. By default, I believe there's a PowerShell shortcut on your taskbar in Server 2012. Right-click on it, and choose "Run as Administrator" (or something like that). Then try running the command in your original post.

mikekol
  • 1,782
  • 12
  • 14
3

Give permissions to HKLM\System\CurrentControlSet\Control\Session Manager\Environment to a desired user

Nipp
  • 103
  • 6
1

I'm running a script in a JEA PSSession as a non-admin user (Administrator permissions are not an option in our environment.) @Nipp's answer pointed me in the right direct (I'll up-vote you when I have enough reputation.) This should work for anyone who wants to allow a non-admin to update environment variables (including Path):

#allow necessary registry permissions to allow updating environment variables
#e.g.:
#Allow-EnvironmentVariableUpdate -Principal 'Power Users'
function Allow-EnvironmentVariableUpdate()
{
    Param(
    [string]$Principal  #name of user or group
    )

    $acl= get-acl -path "hklm:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
    $inherit = [system.security.accesscontrol.InheritanceFlags]"None"
    $propagation = [system.security.accesscontrol.PropagationFlags]"None"
    $rights = "QueryValues,SetValue,CreateSubKey"
    $rule=new-object system.security.accesscontrol.registryaccessrule $Principal,$rights,$inherit,$propagation,"Allow"
    $acl.addaccessrule($rule)
    $acl | set-acl
    "'$Principal' can edit environment variables."
}
f00_b33rd
  • 11
  • 3
0

once try the same command on PowerShell but don't open it directly instead right click on PowerShell and open as administrator; I faced the same problem while setting the environmental variables for minikube https://minikube.sigs.k8s.io/docs/start/ as in

$oldPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine)
if ($oldPath.Split(';') -inotcontains 'C:\minikube'){ `
  [Environment]::SetEnvironmentVariable('Path', $('{0};C:\minikube' -f $oldPath), [EnvironmentVariableTarget]::Machine) `
}

in the above command, we used ::Machine if use as ::User no need to run, but this don't work on minikube start command; in some cases using as ::User works in some of the cases https://github.com/PowerShell/PowerShell-Docker/issues/88#issuecomment-443934635

your problem is almost same as mine so this may work

B M PAVAN
  • 86
  • 7