在Jscript中获取给定用户的特殊文件夹路径

如何为当前用户以外的特定用户获取“本地设置”或“本地Appdata”等shell文件夹的路径?     
已邀请:
虽然有一些方法可以在Windows脚本宿主中获取特殊文件夹路径—
WshShell.SpecialFolders
Shell.NameSpace
—它们只返回当前用户的路径。获取其他用户的特殊文件夹路径有点棘手。 正确的方法是使用WindowsAPI
SHGetKnownFolderPath
功能(或Vista之前的Windows版本上的
SHGetFolderPath
)。但问题是,Windows Script Host不支持调用WinAPI函数,因此要在脚本中使用这些函数,您必须通过自定义编写的COM组件公开它们。 另一种可能但未记录的解决方案是从该用户的注册表配置单元中读取特殊文件夹路径,特别是
HKEY_USERS<user_SID>SoftwareMicrosoftWindowsCurrentVersionExplorerUser Shell Folders
键。
User Shell Folders
键中的路径通常使用
%USERPROFILE%
环境变量指定;因此,要获得完全合格的路径,您必须使用
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionProfileList<user_SID>
键中的
ProfileImagePath
值替换此变量。 此外,
HKEY_USERS<user_SID>
键仅在相应用户当前登录时可用。对于一般解决方案,您必须将用户的配置单元(&lt; UserProfile&gt; ntuser.dat)加载到临时注册表项(例如,
HKEY_USERSTemp
)中,然后从该键读取值。 下面是示例JScript代码,演示如何完成任务。在Windows 7和Vista上,您可能需要以管理员身份运行脚本,具体取决于您的UAC设置。 注意:不鼓励使用这种方法,因为Raymond Chen在他的文章中解释了Shell文件夹密钥的漫长而悲伤的故事。无法保证它将在未来的Windows版本中继续使用。
var strUser = "foo";
var strDomain = "bar";
// If the account is local, domain name = computer name:
// var strDomain = getComputerName();

var strSID = getSID(strUser, strDomain);
var strProfilePath = getProfilePath(strSID);

// Load the user's registry hive into the HKEY_USERSTemp key
var strTempKey = "Temp";
loadHKUHive(strTempKey, strProfilePath + "\ntuser.dat");

// Get unexpanded path, e.g. %USERPROFILE%AppDataRoaming
//var strAppData = getAppData(strSID);
var strAppData = getAppData(strTempKey);
WScript.Echo(strAppData);

// Expand the previous value to a fully-qualified path, e.g. C:UsersfooAppDataRoaming
strAppData = strAppData.replace(/%USERPROFILE%/i, strProfilePath);
WScript.Echo(strAppData);

// Unload the user's registry hive
unloadHKUHive(strTempKey);


function getComputerName() {
   var oShell = new ActiveXObject("WScript.Shell");
   return oShell.ExpandEnvironmentStrings("%COMPUTERNAME%");
}

function getSID(strUser, strDomain) {
    var oAccount = GetObject("winmgmts:root/cimv2:Win32_UserAccount.Name='" + strUser + "',Domain='" + strDomain + "'");
    return oAccount.SID;
}

function getProfilePath(strSID) {
    var oShell = new ActiveXObject("WScript.Shell");
    var strValue = oShell.RegRead("HKLM\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" + strSID + "\ProfileImagePath");
    return strValue;
}

function getAppData(strSID) {
    var oShell = new ActiveXObject("WScript.Shell");
    var strValue = oShell.RegRead("HKEY_USERS\" + strSID + "\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\AppData");
    return strValue;
}

function loadHKUHive(strKeyName, strHiveFile) {
    var oShell = new ActiveXObject("WScript.Shell");
    oShell.Run("reg load HKU\" + strKeyName + " " + strHiveFile, 0, true);
}

function unloadHKUHive(strKeyName) {
    var oShell = new ActiveXObject("WScript.Shell");
    oShell.Run("reg unload HKU\" + strKeyName, 0, true);
}
    

要回复问题请先登录注册