VB App to Batch file

Posted on 2005-04-25
Last Modified: 2008-01-09
Could I please get some help on a project I'm doing. I have this one last area to complete and I just can seem to get it. I have written a VB6.0 app that does a numbr of functions inside a WinPE environement and has function that will ask the user to enter: \\ServerName\Share, USerName and Password so they can map a network drive. I need to pass this information from the VB app to a batch file so the user can map the drive. I have DIM ServerName, UserName and Password and I know these work. How do I place the information collected from the Inputboxes in VB6.0 to a Batch file that will allow a drive to be mapped?

My batch file has the Net Use X: preset. What comes next?
Question by:RBrown1375
    LVL 25

    Expert Comment

    Something like this perhaps:

    @echo off
    if [%~3]==[] (
       set errorlevel=-1
       exit /b
    set drive=%~1
    set server=%~2
    set password=%~3
    net use %drive% "%server%" "%password%"

    Then to use that, you call it like so:

       BatchFileName "X:" "\\ServerName\Share" "password"

    I hope that helps.

    Author Comment

    I may have it wrong but it didn't work. I added the @echo off line all the way down to the net use command into the Batch file and it didn't work. I tried to call the batch file with the Shell "BatchfileName.bat" and the VB app won't pass the collected data from VB to batch. I'm close.
    LVL 25

    Expert Comment

    It won't pass the data? Can't you just do something like this?..

        Shell "BatchFileName.bat x: \\servername\share password"


    ..Be warned, I'm anti-VB  ;-)

    Author Comment

    The VB app asks the Tech to enter:

    A drive letter
    Servername and share

    Once this data is collected, I need the VB app to do a net use command and insert the data the tech entered. Each of those are variables stored in the VB app. I just can get the net use command, to use the information collected.
    LVL 25

    Expert Comment

    If that's all that your VB app does, then can't you just do it all in a Batch file? Like so:

    @echo off
    title Drive Mapper
    set drive=
    set server=
    set username=
    set password=
    set /p drive="Enter the drive letter: "
    set /p server="Enter the servername and share: "
    set /p username="Enter the username: "
    set /p password="Enter the password: "

    if /i "%drive%"=="" echo You must specify a drive& goto :refresh
    if /i "%server%"=="" echo You must specify a servername and share& goto :refresh
    if /i "%username%"=="" echo You must specify a username& goto :refresh
    if /i "%password%"=="" echo You must specify a password& goto :refresh

    set drive=%drive::=%
    set drive=%drive:~0,1%
    if /i "%server:~0,2%" neq "\\" set server=\\%server%

    net use %drive% "%server%" "%password%"


    Author Comment

    Sorry, My VB app runs ghost32, PowerQuest imagecenter32, PQideploy, sets single and dual drive systems, runs partition magic and so on. It has a menu that allows a tech to choose what they want to do. One of the fucntions is to install and image from a network drive with iether ghost or powerquest. I added some fields to the menu to allow a tech to collect the information from my last note and make a network connection without having to close the VB menu, just to do a "net use" function in WinPE and then have to restart the menu to perform other tasks. I want the user to be able to do everything from the VB menu. Everything is working fine except for taking the collected data from the VB menu inboxes and adding it to a batch file so the net use command will connect a drive based on what the user input into the VB menu.
    LVL 49

    Expert Comment

    by:Julian Hansen
    Is there a reason you can't put the map drive code directly into the VB app - do you have to go to a batch file?

    Author Comment

    The mapped drive should be a variable but I guess it doesn't matter. I'd like to use X: or Y: since  Z: is for my RAMDrive. I don't have to use a batch file. What would be the code in VB if I always used:

    Net Use X: \\

    How do I get the ServerName, UserName and Password to run and how can I return a "command completed succsefully " once the Net use command connects the drive?
    LVL 49

    Expert Comment

    by:Julian Hansen
    Post back if these are not helpful

    Here is a link

    Here is some simpler code

    Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias
    "WNetAddConnection2A" (lpNetResource As NETRESOURCE, ByVal lpPassword As
    String, ByVal lpUserName As String, ByVal dwFlags As Long) As Long

    Public Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias
    "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Long,
    ByVal fForce As Long) As Long

    Public Type NETRESOURCE
        dwScope As Long
        dwType As Long
        dwDisplayType As Long
        dwUsage As Long
        lpLocalName As String
        lpRemoteName As String
        lpComment As String
        lpProvider As String
    End Type

    Public Const RESOURCE_GLOBALNET As Long = &H2&
    Public Const RESOURCETYPE_DISK As Long = &H1&

    Public Sub MapDrive(LocalName As String, Remotename As String, Optional
    Username As String, Optional Password As String)
        Dim NetR As NETRESOURCE
        With NetR
            .dwScope = RESOURCE_GLOBALNET
            .dwType = RESOURCETYPE_DISK
            .dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
            .lpLocalName = LocalName
            .lpRemoteName = Remotename
        End With
        WNetAddConnection2 NetR, Password, Username, CONNECT_UPDATE_PROFILE
    End Sub

    Public Sub DisconnectDrive(LocalName As String)
        WNetCancelConnection2 LocalName, CONNECT_UPDATE_PROFILE, False
    End Sub
    LVL 1

    Expert Comment


    Dim WshNetwork
    Set WshNetwork = WScript.CreateObject("WScript.Network")
    WshNetwork.MapNetworkDrive "X:", "\\Server\Public,  [bUpdateProfile], [strUser], [strPassword])"

    Optional. Boolean value indicating whether the mapping information is stored in the current user's profile. If bUpdateProfile is supplied and has a value of true, the mapping is stored in the user profile (the default is false).

    Optional. String value indicating the user name. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

    Optional. String value indicating the user password. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

    For more information:

    LVL 1

    Expert Comment

    Never mind my post.  I was thinking VBscript. not VB6

    Author Comment

    Here is the code I'm using:

    Dim ComputerName, User, Password, Prompt1, Prompt2, Prompt3

    Private Sub LBLPasswordCommand2_Click()
    Prompt1 = "Enter User Password."
    Password = InputBox(Prompt1, "Enter password")

    If Password = "" Then
         MsgBox "User cancelled function.", 48, "Exit"
    End If
    End Sub

    Private Sub LBLServerCommand1_Click()
    Prompt2 = "Enter Server and Share Name."
    ComputerName = InputBox(Prompt2, "Enter Server and Share Name.")

    If ComputerName = "" Then
         MsgBox "User Cancelled Function.", 48, "Exit"
    End If
    End Sub

    Private Sub LBLUserIDCommand1_Click()
    Prompt3 = "Enter User Logon Name."
    User = InputBox(Prompt3, "Enter User ID")

    If User = "" Then
         MsgBox "User Cancelled Function.", 48, "Exit"
    End If
    End Sub

    Private Sub NetworkCommand1_Click()
    If NetworkCommand1.Value = True Then

    What I need goes here. How do I get the variables from above to run with the Net Use X: \\ command?
    I would also like for the window to stay open so the user can see if the command completed correctly.

    End If
    End Sub

    Thanks for the ideas
    LVL 1

    Expert Comment

    Here's an easier solution for you.
    Since batch files are plain text, have your VB app create the batch file dynamically.

    Use FSO to create/overwrite a file named "MapDrive.bat", then write to that file the batch commands.
    "net use X: \\servername\sharename /user:username password"

    Then from your VB app, shell out to this batch file, and delete the file if you wish.  This seems to be a simpler solution than creating a batch to accept parameters or whatnot. I, personally, like to stick to the KISS methodology.

    If you need help writing the app, let me know.

    Author Comment

    I do I have never heard of that.
    LVL 1

    Expert Comment

    This is similar code I use in one of my programs.  Just put the lines of the batch file in the writelines.

    Sub CreateBatchFile()
          Dim fs, a, strPath
          strPath = "pathandfilename.bat"
          Set fs = CreateObject("Scripting.FileSystemObject")
          Set a = fs.CreateTextFile(strPath, True, False)
          a.writeline "Line 1 text"
          a.writeline "Line 2 text"
          a.writeline "Line 3 text"
          a.writeline "Line 4 text"
          a.writeline "Line 5 text"
          Set a = Nothing
          Set fs = Nothing
    End Sub

    Author Comment

    I'll try and let you  know thanks
    LVL 1

    Accepted Solution

    OK. Scratch the batch file all together. Well if you want to create it, it's up to you.

    But, look at (where I got a good chunk of this code). Shows you how to shell out from a VB app.

    Private Type STARTUPINFO
          cb As Long
          lpReserved As String
          lpDesktop As String
          lpTitle As String
          dwX As Long
          dwY As Long
          dwXSize As Long
          dwYSize As Long
          dwXCountChars As Long
          dwYCountChars As Long
          dwFillAttribute As Long
          dwFlags As Long
          wShowWindow As Integer
          cbReserved2 As Integer
          lpReserved2 As Long
          hStdInput As Long
          hStdOutput As Long
          hStdError As Long
       End Type

          hProcess As Long
          hThread As Long
          dwProcessID As Long
          dwThreadID As Long
       End Type

       Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal _
          hHandle As Long, ByVal dwMilliseconds As Long) As Long

       Private Declare Function CreateProcessA Lib "kernel32" (ByVal _
          lpApplicationName As String, ByVal lpCommandLine As String, ByVal _
          lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, _
          ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, _
          ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As String, _
          lpStartupInfo As STARTUPINFO, lpProcessInformation As _

       Private Declare Function CloseHandle Lib "kernel32" _
          (ByVal hObject As Long) As Long

       Private Declare Function GetExitCodeProcess Lib "kernel32" _
          (ByVal hProcess As Long, lpExitCode As Long) As Long

       Private Const NORMAL_PRIORITY_CLASS = &H20&
       Private Const INFINITE = -1&

       Public Function ExecCmd(cmdline$)
          Dim proc As PROCESS_INFORMATION
          Dim start As STARTUPINFO

          ' Initialize the STARTUPINFO structure:
          start.cb = Len(start)

          ' Start the shelled application:
          ret& = CreateProcessA(vbNullString, cmdline$, 0&, 0&, 1&, _
             NORMAL_PRIORITY_CLASS, 0&, vbNullString, start, proc)

          ' Wait for the shelled application to finish:
             ret& = WaitForSingleObject(proc.hProcess, INFINITE)
             Call GetExitCodeProcess(proc.hProcess, ret&)
             Call CloseHandle(proc.hThread)
             Call CloseHandle(proc.hProcess)
             ExecCmd = ret&
       End Function

    Function MapDrive(strDriveLetter as string, strServerShare as string, strUserName as string, strPassword as string)
          Dim retval As Long
          Dim strCommand as string
          strCommand = "net use " & strDriveLetter & ": " & strServerShare & " /user:"&strUserName & " " & strPassword
          retval = ExecCmd(strCommand)
          MapDrive = retval
    End Function
    LVL 1

    Expert Comment

    Sorry schumakers, I posted my previous entry before reading your entry. I didn't mean to be offensive to your solution.
    LVL 1

    Expert Comment

    I would do it programatically as they have shown you.  If you want a less complex way of doing it then creating a batch file also works.

    No offense taken.  Just saw the post and new I had that code already made.  So, I posted it.
    LVL 1

    Expert Comment

    Oh yes, and BTW, the MapDrive function will return the same ERRORLEVEL as the "net use" command. That way you can track if the "net use" succeeded or not.
    0 = successful, other errorlevel = error.

    Author Comment


    Thank You. I didn't need all the code but the final area Function MaPdrive worked after I altered it to meet my needs.

    Cheers and have a great day!!!!

    Thanks to everyone who answered!
    LVL 1

    Expert Comment

    No Problem.

    FYI: I'm not sure of the consequences of not including all that code since most of the code are supporting functions for ExecCmd(). Most of it was directly from microsoft. That's what I have in my program and it's been working for 2 years w/o a hitch. But it's up to you if you don't want to include it all.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    post4 challenge 28 70
    Changing the installation path of this MSI 5 75
    How to split this in C++ 4 51
    count8 challlenge 13 67
    RIA (Rich Internet Application) tools are interactive internet applications which have many of the characteristics of desktop applications. The RIA tools typically deliver output either by the way of a site-specific browser or via browser plug-in. T…
    Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
    In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now