从 windows 服务设置注册表不起作用

Setting Registry from windows service does not work

我正在设置或读取作为本地系统运行的 windows 服务的注册表项。 但是当我在注册表编辑器中读取或设置值时,它们与我从 windows 服务读取和设置它们时不同。

如果我从 windows 服务在 powershell 中执行以下命令,或者当我以用户身份登录时,结果也会不同。为什么? LocalSystem 帐户是否有不同的 LocalMachine?

$DefaultUserName = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name "DefaultUserName").DefaultUserName
Write-Host $DefaultUserName 

我正在使用以下 c# 行从 windows 服务执行 powershell 脚本:

var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
process.StartInfo.Arguments = "\"&'" + cacheFile + "'\"";
process.StartInfo.Verb = "runas";
process.Start();

这个答案对 Windows 内置帐户有很好的解释: The difference between the 'Local System' account and the 'Network Service' account?

A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user

Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

你也可以尝试 运行 服务作为 SYSTEM 吗?

你需要注意位数。在 64 位 Windows 上,32 位应用程序 运行 使用 'Windows on Windows' 子系统,默认情况下使用不同的文件系统路径和注册表路径。您正在从 SysWOW64 文件夹执行 powershell,这意味着您正在执行 32 位版本,它将使用 32 位注册表配置单元。

如果您打开 regedit,您的注册表项的 32 位配置单元是:Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\Winlogon。我怀疑你是getting/setting这个值

请参阅 How to access a 64Bit Registry key using 32Bit Powershell without Redirection to WOW6432Node 了解您可以采取的策略,包括使用 Sysnative 而不是 SysWOW64 版本的 powershell。

如果您需要支持 32 位和 64 位操作系统,则需要确保您使用了适当的技术。