当 运行 作为另一个用户 [admin] 时,在 NSIS 安装程序中获取登录用户名

Get logged in username in NSIS installer when running as another user [admin]

我创建了一个需要提升权限的 NSIS 安装程序,并且还在用户 AppData 目录中安装了一些文件。只要当前用户是管理员,这就可以正常工作。如果用户是受限用户,则他们必须 运行 安装程序作为管理员,将管理员凭据传递给安装程序。除了在这种情况下 NSIS 将文件安装到管理员用户 AppData 目录之外,这一切都很好。这是因为我一直在使用 $PROFILE 变量来确定文件的安装位置,但是 $PROFILE returns 用户的路径是 运行 安装程序而不是登录系统的用户。

所以要明确一点,如果 User A 是受限帐户而 User B 是管理员帐户,当我使用 User A 和 运行 登录计算机时安装程序,传递 User B 的凭据,我只能从 NSIS 获取 User B 的用户名,因此无法为 User A.

安装必要的文件

我目前使用的是 NSIS v2.49,我已经 2 年多没有更新了,所以我认为它已经过时了。在撰写本文时,sourceforge 上的 NSIS 站点已经关闭几天,因此很难找到该软件的最新副本。我愿意升级到 NSIS v3.x 如果有人能指出这如何帮助解决这个问题。

下面是一些非常简单的代码来演示我的问题。如果您构建此安装程序并 运行 它在受限用户桌面上,它将演示 3 种不同的尝试来获取当前登录的用户名,但所有 3 次都会带回 运行ning 的用户名安装程序改为:

Outfile Test.exe
RequestExecutionLevel admin ;Require admin rights on NT6+ (When UAC is turned on)

!include LogicLib.nsh

Function .onInit
UserInfo::GetAccountType
pop [=11=]
${If} [=11=] != "admin" ;Require admin rights on NT4+
    MessageBox mb_iconstop "Administrator rights required!"
    SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED
    Quit
${EndIf}

MessageBox MB_OK $PROFILE
System::Call "advapi32::GetUserName(t .r0, *i ${NSIS_MAX_STRLEN} r1) i.r2"
MessageBox MB_OK "User name Test 1: [=11=]"
ReadEnvStr [=11=] "USERNAME" 
MessageBox MB_OK "User name Test 2: [=11=]" 

FunctionEnd

Page instfiles

Section
SectionEnd

当 运行将安装程序设置为另一个用户时,NSIS 安装程序是否无法确定登录用户的用户名?

这就是 UAC 的工作原理。

如果您需要提升,那么您正在执行 machine/all 用户安装,您应该只写入 $ProgramFiles 和 HKLM。将 SetShellVarContext all 添加到 .onInit 函数以防止写入用户配置文件。您还应该禁用完成页面上的 运行 复选框。

如果您的应用程序需要 $AppData 中的数据,那么应用程序应在用户首次 运行s 时将模板数据从 $ProgramFiles、ProgramData (SetShellVarContext all + $AppData) 或 $COMMONFILES 复制到 $AppData你的申请。至少从 Windows 2000 年开始,这就是 Windows 徽标计划的要求!

您可以在 Certification requirements for Windows desktop apps or the older Windows Logo requirements 文档中找到这些建议:

10.3 Your app data, which must be shared among users on the computer, should be stored within ProgramData

10.4 Your app’s data that is exclusive to a specific user and that is not to be shared with other users of the computer, must be stored in Users\%username%\AppData

10.6 Your app must write user data at first run and not during the installation in “per-machine” installations

When the app is installed, there is no correct user location in which to store data. Attempts by an app to modify default association behaviors at a machine level after installation will be unsuccessful. Instead, defaults must be claimed on a per-user level, which prevents multiple users from overwriting each other's defaults.