How Can I Determine if a Users’ Folder Exists on a Computer?

ScriptingGuy1

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I determine if the C:\Documents and Settings\%username%\Application Data\Microsoft\Templates folder exists on a computer?

— JM

SpacerHey, Scripting Guy! AnswerScript Center

Hey, JM. The FileSystemObject includes a FolderExists method that makes it very easy to check for the existence of a folder. Just pass FolderExists the complete path to the folder and you’ll quickly get back True if the Folder exists and False if the folder does not exist.

The only catch here is that you don’t necessarily know the complete path to the folder; after all, each user who logs on is going to have a different path to the Templates folder; that’s because %username% is different for each user.

But that’s OK: we can easily figure out the value of %username%, and then use that value to construct the path to the Templates folder. Let’s show you a script that checks for the existence of the C:\Documents and Settings\%username%\Application Data\Microsoft\Templates folder, and then we’ll explain how it works:

Set objNetwork = CreateObject(“Wscript.Network”)
strUser = objNetwork.UserName

strPath = “C:\Documents and Settings\” & strUser & “\Application Data\Microsoft\Templates”

Set objFSO = CreateObject(“Scripting.FileSystemObject”)

If objFSO.FolderExists(strPath) Then Wscript.Echo “The folder exists.” Else Wscript.Echo “The folder does not exist.” End If

We begin by creating an instance of the Wscript.Network object, and then storing the value of the UserName property in a variable named strUser. Because UserName happens to have the same value as the %username% environment variable we can now construct the exact path to the Templates folder. That’s what we do in this line of code, which simply adds C:\Documents and Settings\ plus the value of strUser plus \Application Data\Microsoft\Templates:

strPath = “C:\Documents and Settings\” & strUser & “\Application Data\Microsoft\Templates”

If our user happens to be named kmyer, we’ll now have a path that looks like this:

C:\Documents and Settings\kmyer\Application Data\Microsoft\Templates

The rest is easy. We create an instance of the FileSystemObject and use the FolderExists method to determine whether the folder C:\Documents and Settings\kmyer\Application Data\Microsoft\Templates exists or not. We echo back the answer – yes, the folder exists or no, the folder does not exist – and we’re done.

0 comments

Discussion is closed.

Feedback usabilla icon