-2

My problem is that I need to find a VBScript way to retrieve the value of %USERNAME% to get the user profile folder - for example, C:\%USERNAME%\Documents\example.txt.

How do I get the %USERNAME% from VBScript?

(Edited) I don't know anything about vb so i don't know about strings or wscript or anything like that. explain it to me as if i was a child, where to put the script and etc Thanks

Big fat .BAT
  • 49
  • 1
  • 1
  • 4
  • 4
    Possible duplicate of [Can I pick up environment variables in vbscript WSH script?](http://stackoverflow.com/questions/904739/can-i-pick-up-environment-variables-in-vbscript-wsh-script) – FloatingKiwi Aug 18 '16 at 03:57

5 Answers5

3

See this answer: https://stackoverflow.com/a/904747/6550457

I'd recommend using %USERPROFILE% instead of %USERNAME% if you're after the standard windows profile directory.

Community
  • 1
  • 1
FloatingKiwi
  • 4,408
  • 1
  • 17
  • 41
1

While the other answers (and proposed duplicate) is answering the question you are asking, about expanding environment variables, it looks like you're actually trying to get the user's Documents folder. This can be done via the Shell object's SpecialFolder collection:

Set objShell = WScript.CreateObject("WScript.Shell")
strDocumentDirectoryPath = objShell.SpecialFolders.Item("MyDocuments")

See more details in the WSH SpecialFolders documentation.

0

With this sample code you can did the trick :

Set Ws = CreateObject("WScript.Shell")
UserName=Ws.ExpandEnvironmentStrings("%UserName%")
ComputerName=Ws.ExpandEnvironmentStrings("%ComputerName%")
WScript.Echo "The UserName is : "& UserName 
Wscript.echo "The computername is : " & ComputerName
wscript.echo "C:\"& USERNAME & "\Documents\example.txt"
Hackoo
  • 18,337
  • 3
  • 40
  • 70
0
Set WshShell = WScript.CreateObject("WScript.Shell")
CurrentProfilePath = WshShell.RegRead("HKCU\Volatile Environment\USERPROFILE")
Randy Schuman
  • 357
  • 1
  • 9
-1

Returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString) 

object

WshShell object.

strString

String value indicating the name of the environment variable you want to expand.

Not spelt out above. Pass a whole string to it if it's a path or something. EG %windir%\system32 works fine and returns c:\windows\system32..

However this is not the VBS way to do what what you want. Any program or user can screw up environmental variables.

Returns the name of a user.

object.UserName 

object

WshNetwork object.