查找当前用户 [英] Finding current user
问题描述
我正在尝试编写一个 VBS 脚本来复制另一台计算机上的文件,而无需将其用户名手动输入到我的脚本中.脚本中 USER 的位置是我需要放置当前用户的位置.
I'm trying to write a VBS script to copy files on another computer without manually entering their username into my script. Where it says USER in the script is where I need to put the current user.
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists("C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\")) Then
FSO.CopyFile "V.VBS", "C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"
FSO.CopyFile "M.mp3", "C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\"
Else
End If
推荐答案
获取当前用户名的方法有多种,例如
There are several ways to obtain the name of the current user, for instance
Set net = CreateObject("WScript.Network")
username = net.UserName
或通过扩展 %USERNAME%
环境变量
or by expanding the %USERNAME%
environment variable
Set sh = CreateObject("WScript.Shell")
username = sh.ExpandEnvironmentVariables("%USERNAME%")
一旦你有了 usrename,你就可以像这样构建你的路径字符串:
Once you have the usrename you can build your path string like this:
Set fso = CreateObject("Scripting.FileSystemObject")
profile = fso.BuildPath("C:\Users", username)
startup = fso.BuildPath(profile, "AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup")
<小时>
由于您使用的是用户 AppData
文件夹的子文件夹,您还可以展开 %APPDATA%
变量而不是 %USERNAME%代码>变量:
Since you're working with a subfolder of the user's AppData
folder you could also expand the %APPDATA%
variable instead of the %USERNAME%
variable:
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
appdata = fso.BuildPath("C:\Users", sh.ExpandEnvironmentVariables("%APPDATA%"))
startup = fso.BuildPath(appdata, "Microsoft\Windows\Start Menu\Programs\Startup")
<小时>
另一种选择是从注册表中读取启动文件夹位置并在返回的路径字符串中展开环境变量:
Another option would be to read the startup folder location from the registry and expand the environment variable(s) in the returned path string:
regpath = "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Startup"
Set sh = CreateObject("WScript.Shell")
startup = sh.ExpandEnvironmentStrings(sh.RegRead(regpath))
这篇关于查找当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!