以SYSTEM权限运行的提权脚本如何获取普通用户的环境变量?
解决方案
SYSTEM账号的用户配置文件默认路径为C:\Windows\System32\config\system,因此在SYSTEM上下文下直接读取$env:APPDATA得到的是SYSTEM账号的对应路径,和当前登录普通用户无关。你可以通过已获取的登录用户名,查询对应用户的SID后读取其注册表配置,获取包括AppData在内的所有用户专属路径:
完整实现代码
# 获取当前控制台登录的完整用户名(格式:域名\用户名 或 计算机名\用户名) $fullLoginUser = (Get-CimInstance CIM_ComputerSystem).Username # 拆分域名/计算机名、用户名 $domainPart, $userPart = $fullLoginUser -split '\\', 2 # 转换用户名得到用户SID $userSid = (New-Object System.Security.Principal.NTAccount($domainPart, $userPart)).Translate([System.Security.Principal.SecurityIdentifier]).Value # 读取用户AppData(Roaming)路径 $userAppData = Get-ItemPropertyValue -Path "Registry::HKEY_USERS\$userSid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -Name "AppData" # 读取用户Local AppData路径(可选) $userLocalAppData = Get-ItemPropertyValue -Path "Registry::HKEY_USERS\$userSid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -Name "Local AppData" # 读取用户用户目录路径(可选) $userProfile = Get-ItemPropertyValue -Path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$userSid" -Name "ProfileImagePath"
说明
- 该方案仅适用于用户已完成登录的场景,此时用户的注册表配置单元已挂载到
HKEY_USERS路径下可直接读取 - 如需获取其他用户专属路径,可以查看
HKEY_USERS\$userSid\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders下的其他键值,常用的包括Desktop(桌面)、Personal(文档)、Startup(启动菜单)等
内容的提问来源于stack exchange,提问作者user736893
相关产品推荐
相关产品推荐

