Powershell:永久修改路径,“请求的注册表访问被拒绝。”

10

我需要将一个脚本文件夹永久添加到我的PowerShell路径中(不仅仅是在当前会话中)。我正在运行以下代码:

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

错误如下:

使用"3"个参数调用"SetEnvironmentVariable"时出现异常:"不允许访问请求的注册表。"

如何获得注册表访问权限/修复此问题?

编辑: 不确定是否有帮助,但我正在使用Windows Server 2012上的PowerCLI(VMware PowerShell API)。


你是否以管理员身份运行? - mikekol
说实话我不确定。我对这个还很新。有没有什么简单的方法可以找出来? - corneria
1
假设您不是管理员。在Server 2012上,默认情况下,我相信任务栏上有一个PowerShell快捷方式。右键单击它,选择“以管理员身份运行”(或类似选项)。然后尝试运行您原始帖子中的命令。 - mikekol
确实可以运行。谢谢。 - corneria
如果你在这个帖子中“回答”,我会接受。 - corneria
4个回答

14

听起来您可能没有以管理员身份运行。默认情况下,我相信在您的Server 2012任务栏上有一个PowerShell快捷方式。右键单击它,然后选择“以管理员身份运行”(或类似选项)。然后尝试在原始帖子中运行该命令。


3
给予一个期望的用户对于HKLM\System\CurrentControlSet\Control\Session Manager\Environment的权限。

1
我正在以非管理员用户身份在JEA PSSession中运行脚本(在我们的环境中,无法使用管理员权限)。@Nipp的答案指引了我正确的方向(当我有足够的声望时,我会给你点赞。)这对于任何想允许非管理员更新环境变量(包括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."
}

此答案允许指定用户在不升级为管理员状态的情况下设置这些值。 - 110100100

0

尝试在PowerShell上执行相同的命令,但不要直接打开它,而是右键单击PowerShell并以管理员身份运行; 我在设置minikube https://minikube.sigs.k8s.io/docs/start/ 的环境变量时遇到了相同的问题。

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

在上面的命令中,我们使用了::Machine,如果使用::User则不需要运行,但这在minikube start命令中不起作用;在某些情况下,将其用作::User可行,在一些情况下不可行。https://github.com/PowerShell/PowerShell-Docker/issues/88#issuecomment-443934635 你的问题和我的几乎相同,所以这可能有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接