0

I'm coding a new VBS script, which should create a TXT file in the Documents directory. While with other inputs I used %USERNAME% for the User Name of the PC, the command "CreateTextFile" seems to want the real directory, without including any variables like %USERNAME%.

I'm kinda of new to this so I can't figure it out.

That's what I tried:

Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("C:\Users\%USERNAME%\Documents\Demo.txt", true)
objFile.WriteLine("some sample text")

It should understand %USERNAME% as the UserName of the PC, but doesn't.

What I get as result is the program saying he can't find the directory C:\Users\%USERNAME%\Documents.

  • Possible duplicate of [Make VBScript check for a file with a certain word in it's file name and then find and delete that file](https://stackoverflow.com/questions/30136645/make-vbscript-check-for-a-file-with-a-certain-word-in-its-file-name-and-then-fi) – JosefZ Apr 08 '19 at 17:47
  • @JosefZ that's very specific, but I don't see where the OP mentions anything about checking for a particular word in a file and deleting it? – user692942 Apr 09 '19 at 08:37
  • 1
    Possible duplicate of [Can I pick up environment variables in vbscript WSH script?](https://stackoverflow.com/questions/904739/can-i-pick-up-environment-variables-in-vbscript-wsh-script) – user692942 Apr 09 '19 at 08:39

2 Answers2

0

To get the desktop one uses

SpecialFolders Property

Returns a SpecialFolders object (a collection of special folders).

object.SpecialFolders(objWshSpecialFolders)

Arguments

object WshShell object.

objWshSpecialFolders The name of the special folder. (eg Desktop)

Environment strings are not expanded. You can pass an entire string containing environmental variables. EG "%userprofile%\Desktop". This code lists all variables available https://pastebin.com/rrEyVxFd.

ExpandEnvironmentStrings Method

Returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString)

Arguments

object WshShell object.

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

Noodles
  • 264
  • 2
  • 3
0

There are plenty longer drawn-out, which are appropriate but these are a couple examples - much easier:

Option Explicit

Msgbox CreateObject("WScript.Network").UserName

' or into a variable

Dim oShell : set oShell = CreateObject("WScript.Network")
Dim UserName : UserName = oShell.UserName
Msgbox UserName

Set oShell = Nothing
Theo
  • 57,719
  • 8
  • 24
  • 41
svstackoverflow
  • 665
  • 6
  • 19