在 VBA 中使用 CreateProcess 和 Powershell Start-Process 时,Set-ItemProperty 找不到路径

Set-ItemProperty can't find path when using CreateProcess and Powershell Start-Process in VBA

我需要使用 CreateProcess 和 Powershell 从 VBA 脚本更改注册码。下面你会找到我的 VBA 代码。

当我直接在 Powershell 中 运行 引号内的代码或使用 windows 运行 时,注册表项会按应有的方式设置。当我使用此 VBA 代码时出现路径错误。

路径完全正确。在同一个 VBA 脚本中,我使用相同的命令设置了一些其他注册键,没有出现错误。我不知道错误可能是什么。我在两个新的 Windows 10 个虚拟机上测试了脚本,结果相同。

提前感谢您的帮助。

Dim pInfo As PROCESS_INFORMATION
Dim sInfo As STARTUPINFO
Dim sNull As String
Dim lSuccess As Long
Dim lRetValue As Long

lSuccess = CreateProcess(sNull, "powershell start-process -filepath powershell.exe -Argumentlist 'Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows` Defender` Security` Center\Notifications -Name DisableNotifications -Value 1' -verb RunAs -windowstyle hidden -Wait", ByVal 0&, ByVal 0&, 1&, CREATE_NO_WINDOW, ByVal 0&, sNull, sInfo, pInfo)
Set-ItemProperty : Der Pfad "HKLM:\SOFTWARE\Microsoft\Windows Defender Security Center\Notifications" kann nicht
gefunden werden, da er nicht vorhanden ist.
In C:\Users\public\psc.ps1:9 Zeichen:1
+ Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows` Defender` Se ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (HKLM:\SOFTWARE\...r\Notifications:String) [Set-ItemProperty], ItemNotFo
   undException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetItemPropertyCommand


Note---------------------------------------
(The german stuff at the beginning means the following)
The path "HKLM:\SOFTWARE\Microsoft\Windows Defender Security Center\Notifications" cannot be found, because it does not exist"

编辑 1:

令人惊讶的是,当我 运行 我刚才在那里找到的脚本时,reg 密钥正在我的开发虚拟机上设置。所以我假设 Windows 或安装的软件有问题。我已经测试了所有我能想到的差异,但没有成功

我认为你的报价有问题。我建议你在路径周围加上 2 个单引号并删除路径中的 `:

例如

$mystring = 'Get-ItemProperty -Path ''HKLM:\SOFTWARE\Microsoft\Windows Defender Security Center\Notifications'''
$mystring

这将导致输出:

Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows Defender Security Center\Notifications'

因此您的代码应如下所示:

Dim pInfo As PROCESS_INFORMATION
Dim sInfo As STARTUPINFO
Dim sNull As String
Dim lSuccess As Long
Dim lRetValue As Long

lSuccess = CreateProcess(sNull, "powershell start-process -filepath powershell.exe -Argumentlist 'Set-ItemProperty -Path ''HKLM:\SOFTWARE\Microsoft\Windows Defender Security Center\Notifications'' -Name DisableNotifications -Value 1' -verb RunAs -windowstyle hidden -Wait", ByVal 0&, ByVal 0&, 1&, CREATE_NO_WINDOW, ByVal 0&, sNull, sInfo, pInfo)

EDIT1:所以我终于找到了这个问题的真正解决方案和原因。如旧“解决方案”中所述,32 位和 64 位版本的 Office 之间存在问题。我尝试使用 reg add 设置注册表值并发现,它向 WOW6432 写入了 32 位应用程序的兼容层。如果您知道它存在,那将是非常明显的,因为 Office 通常是 32 位应用程序。我假设找不到路径,因为 powershell 在 32 位 Office 的上下文中是 运行 并尝试访问注册表的 64 位部分。 reg add 命令在 WOW6432 中设置值,这将不起作用,因为 Windows Defender 安全中心不读取那里的值。但是有一个 /reg:64 标志,它强制 reg add 写入注册表的 64 位部分。一切正常。