Check if folder is there, if not create it on current user logged in VBS

user2281912 picture user2281912 · Jun 4, 2013 · Viewed 82.1k times · Source

Currently this is my script

Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )

What I am trying to do is grab the current user logged in, I want it to check the directory D:\"personsuser"\Appdata\Roaming\Local to see if the folder "Local" is created, if it isn't created I want to create one via createobject in vbs. The script above from what i know grabs the current logged on user, however i'm not sure how to use this variable to create a folder.

I know i will have to incorporate something along these lines:

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder("C:\FSO")

And or something along these lines:

Dim objNetwork
Dim userName
Dim FSO

Set FSO = CreateObject("Scripting.FileSystemObject")

Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName

If fso.driveExists("D:\" & userName & "\AppData\Local\") Then
    FSO.CreateDirectory ("D:\" & userName & "\AppData\Local\")
End If

Thanks in advance, not very familiar with VBS however that is the only platform I can operate from in the environment that i'm using it.

Answer

Daniel Holman picture Daniel Holman · Jun 4, 2013
Set oWS = WScript.CreateObject("WScript.Shell")
' Get the %userprofile% in a variable, or else it won't be recognized
userProfile = oWS.ExpandEnvironmentStrings( "%userprofile%" )

Dim objNetwork
Dim userName
Dim FSO
Dim Folder

Set FSO = CreateObject("Scripting.FileSystemObject")

Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.userName

If NOT (FSO.FolderExists(userProfile + "\AppData\Roaming\Local")) Then
    ' Delete this if you don't want the MsgBox to show
    MsgBox("Local folder doesn't exists, creating...")
    splitString = Split(userProfile, "\")

    ' Create folder
    MsgBox("D:\" + splitString(2) + "\AppData\Roaming\Local")
    'FSO.CreateFolder(splitString(2) + "\AppData\Roaming\Local")
End If

Here you go man, this should work perfect, regards Daniel.