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.

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.