Powershell 使用备用凭据编辑 HKLM 注册表

Powershell edit HKLM registry with alternate credentials

尝试使用 Set-ItemProperty 使用备用管理员凭据设置 HKLM 注册表,但出现错误,"The provider does not support the use of credentials." 而 运行 此脚本作为标准最终用户将不会有对我们要编辑的 HKLM 值的写入权限。

$RegKey1 ='HKLM:\SOFTWARE\Microsoft\Office\Outlook\Addins\Workshare.Client.OutlookFormUI.AddinModule'

$username = "LocalAdmin"
$password = "Passw0rd"
$AdminCred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))

Set-ItemProperty -Path $RegKey1 -Name "LoadBehavior" -Value 2 -Credential $AdminCred

来自 Get-Help Set-ItemProperty - 详细信息:

-Credential Specifies a user account that has permission to perform this action. The default is the current user.

Type a user name, such as "User01" or "Domain01\User01", or enter a PSCredential object, such as one generated by the Get-Credentia l cmdlet. If you type a user name, you will be prompted for a password.

This parameter is not supported by any providers installed with Windows PowerShell.

获取-PS提供商 | FT -AutoSize

Name        Capabilities                       Drives
----        ------------                       ------
Registry    ShouldProcess, Transactions        {HKLM, HKCU}
Alias       ShouldProcess                      {Alias}
Environment ShouldProcess                      {Env}
FileSystem  Filter, ShouldProcess, Credentials {C, D, E}
Function    ShouldProcess                      {Function}
Variable    ShouldProcess                      {Variable}
Certificate ShouldProcess                      {Cert}

(自 PS 3.0 起,文件系统提供程序具有 'Credentials' 功能)

如您所见,注册表提供商不支持凭据。此参数仅适用于将使用 Set-ItemProperty 通用命令并可能添加 'Credentials' 支持他们自己的远程计算机连接方式的其他自定义提供程序。

如果您想实现目标,请使用 PS Remoting、WMI、Remote Registry PowerShell 模块或 Jerry Lai 建议。

解决方案是创建一个包含所有所需 HKLM 更改的 reg 文件,并使用带有 -credentials 参数的启动进程来执行 reg.exe。

$username = "mydomain\localdmin"
$password = "Passw0rd"
$AdminCred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$regFile = "\myServer\myShare\myRegFile.reg"
$regArg1 = "import $regFile"

Start-Process reg.exe -ArgumentList $regArg1 -Credential $AdminCred