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

痴心易碎 提交于 2020-01-31 07:03:04

问题


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.


回答1:


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.




回答2:


Here is code part from my utilty for FSO:

dim ffso

Function GetFSO
    if not IsValidObject(ffso) then set ffso = CreateObject("Scripting.FileSystemObject")
  Set GetFSO = ffso
End Function

sub SureDirectoryExists(ADir)
    if ADir="" then exit sub
    if not GetFSO().FolderExists(ADir) then
        SureDirectoryExists ffso.GetParentFolderName(ADir)
        ffso.CreateFolder ADir
    end if
end sub


来源:https://stackoverflow.com/questions/16909365/check-if-folder-is-there-if-not-create-it-on-current-user-logged-in-vbs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!