简体   繁体   English

%USERNAME%变量选择了错误的用户名

[英]Wrong username picked by the %USERNAME% variable

Some login problem came with my previous user account. 我以前的用户帐户出现了一些登录问题。 Therefore, the Admin created a new User account for me in the same PC. 因此,管理员在同一台PC上为我创建了一个新的用户帐户。

PROBLEM: Now I have to write a common script (which will be used in other PCs too). 问题:现在我必须编写一个通用脚本(也将在其他PC中使用)。 In this script I have to specify the path of Desktop . 在此脚本中,我必须指定Desktop的路径。 I am using the following command (only example here) line which works everywhere except my PC 我正在使用以下命令(仅在此处为示例)这行适用于除我的PC之外的所有地方

cd "C:\Users\%USERNAME%\Desktop"
pause 

It is not working in my PC because it is assigning the old username to the %USERNAME% variable and therefore trying to enter the Desktop of previous username which does not exist anymore (I removed the old user folder). 它无法在我的PC上运行,因为它正在将旧的用户名分配给%USERNAME%变量,因此尝试输入不再存在的先前用户名的桌面(我删除了旧用户文件夹)。

How can I get the correct user name (new user name) assigned to the %USERNAME% variable? 如何获得分配给%USERNAME%变量的正确用户名(新用户名)?

You can retrieve the folder configured as Desktop for the current user from the registry 您可以从注册表中为当前用户检索配置为桌面的文件夹

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=2,*" %%a in ('
        reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v desktop
        ^| find "REG_"
    ') do call set "desktopFolder=%%b"

    echo %desktopFolder%

Note that as by default the registry key requested is of REG_EXPAND_SZ type, it can contain environment variables references that need to be expanded. 请注意,默认情况下,请求的注册表项是REG_EXPAND_SZ类型,它可以包含需要扩展的环境变量引用。 That is the reason for the call set and not a direct set , we need to force a second parse of the retrieved value to get a full expanded folder path. 这就是call set而不是直接set ,我们需要强制对检索到的值进行第二次解析以获取完整的扩展文件夹路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM