Announcement

Collapse
No announcement yet.

VBScript mapping a drive with a username and password

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • VBScript mapping a drive with a username and password

    Hello, I read on one of the threads about how to map a drive on a different domain with a username and password. Here is the script:

    Set objNetwork = WScript.CreateObject("WScript.Network")
    strLocalDrive = "K:"
    strRemoteShare = "\\server\share"
    strPer = "FALSE"
    strUsr = InputBox("Please Enter Your Username")
    strPas = InputBox("Please Enter your Email Password")
    objNetwork.MapNetworkDrive strLocalDrive, strRemoteShare, strPer, strUsr, strPas
    mDrive = "K:"
    Set oShell = CreateObject("Shell.Application")
    oShell.NameSpace(mDrive).Self.Name = "share name"

    Now first off this works great when the user logs in correctly. When you cancel the box out or typo the logon it fails and prompts the VBS error. Basically it does not look pretty when they fail. Any ideas on how to dress it up a bit to make it not fail so badly and the user has to reloggin to map the drive?

    If itís to log of a script to post here I understand.

    Also is there anyway to dress up the input username box with a picture maybe a logo?

    Thanks!!

  • #2
    Re: VBScript mapping a drive with a username and password

    Nice script MetalSmith

    You can add the line: on Error Resume next to the script, before the line where the script tries to make the drive mapping. Then the script will continues with the next line after an error might occurred.

    Secondly,
    you can add name conditions to the script. In the next example the inputbox expects an username that is longer than 2 characters, and a password longer than 3 characters. You can change these values if you like.

    An otherthing... after you have added the line "on Error..." and the script first tries to do the drive mapping, when that fails now it will continue with the drive name changing. -But what will happen if the drive letter might already exists and is mapped to an other share- the script will not try to re-map the drive but it give an error instead, but then it will continue with changing name of the wrong mapping. To avoid that from happening I added a simple error handling in the example script, it will continue with the naming only if the error level is 0.
    Code:
    on Error Resume Next
    
    ' *** variables
    mDrive = "K:"
    strRemoteShare = "\\server\share"
    strUPNsuffix = "@domain.com"
    
    strPer = "FALSE"
    
    minUSRnamelength = 2
    minPASSwrdlength = 3
    
    
    ' *** InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
    ' *** & Map drive using the entered credentials
    
    Set objNetwork = WScript.CreateObject("WScript.Network")
    Set oShell = CreateObject("Shell.Application")
    
    strUsr = InputBox(vbcrlf& vbcrlf& "Confirm your Username","Enter Your Username",objNetwork.username)
     If Not Len(strUsr) < minUSRnamelength then
         strUsr = Ucase(strUsr) & strUPNsuffix  '<--- adds the UPNsuffix to the account
         strPas = InputBox(vbcrlf& "Please enter " & vbcrlf& strUsr & "'s" & vbcrlf& vbcrlf& "email Password:")
          if Not Len(strPas) < minPASSwrdlength then
             Err.Clear
             objNetwork.MapNetworkDrive mDrive, strRemoteShare, strPer, strUsr, strPas
              If Err.Number = 0 Then
                 oShell.NameSpace(mDrive).Self.Name = "share name"
              End If
           End If
     End If
    
    Set oShell = Nothing
    wscript.quit 0
    
    
    ' *** How can I mask Passwors Using an InputBox?
    ' http://www.microsoft.com/technet/scriptcenter/resources/qanda/feb05/hey0204.mspx
    ' *** How Can I Specify a Window Size for My HTA?
    'http://www.microsoft.com/technet/scriptcenter/resources/qanda/sept05/hey0919.mspx
    \Rems


    EDIT--
    I forgot to tell... quote: "Also is there anyway to dress up the input username box with a picture maybe a logo?"
    The last lines in the example script are some links, there you can see how to use HTA for creating an InputBox.
    With HTA you can combine 'simple' vbscript with html code. Now with html you have the possibilities to dressup the inputbox with collors and logo's.
    Last edited by Rems; 4th May 2007, 08:34. Reason: add upn suffix automatically

    This posting is provided "AS IS" with no warranties, and confers no rights.

    __________________

    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts

    Comment


    • #3
      Re: VBScript mapping a drive with a username and password

      Here is an idea of how mapping_with_credentials can be done with a HTA-script.

      - The user interface part is between: [body ] and [/body] and that part is in HTML-code. There you can insert Images, change fonts and collors if you want to dress the user interface.
      - In the HTA:APPLICATION part of the file, you can modify window_type (more options to use here).
      - Next, at "Window_Onload"at the beginning of the <SCRIPT LANGUAGE="VBScript"> there you have the options for the window_sizing.

      Code:
      <HTML>
      <HEAD>
      <TITLE>Map drive K: to trusted domain</title>
      <HTA:APPLICATION
           ApplicationName="MappingWithCredentials.HTA"
           SingleInstance="Yes"
           WindowsState="Normal"
           Scroll="No"
           Navigable="Yes"
           MaximizeButton="No"
           SysMenu="Yes"
           Caption="Yes"
      ></HEAD>
      
      <SCRIPT LANGUAGE="VBScript">
      
      Sub Window_Onload
        '# Size Window
        sHorizontal = 440
        sVertical = 175
        Window.resizeTo sHorizontal, sVertical
        '# Get Monitor Details
        Set objWMIService = GetObject _
          ("winmgmts:root\cimv2")
        intHorizontal = sHorizontal *2
        intVertical = sVertical *2
        Set colItems = objWMIService.ExecQuery( _
          "Select ScreenWidth, ScreenHeight from" _
          & " Win32_DesktopMonitor", , 48)
        For Each objItem In colItems
          sWidth= objItem.ScreenWidth
          sHeight = objItem.ScreenHeight
          If sWidth > sHorizontal _
            then intHorizontal = sWidth
          If sHeight > sVertical _
            then intVertical = sHeight
        Next
        Set objWMIService = Nothing
        '# Center window on the screen
        intLeft = (intHorizontal - sHorizontal) /2
        intTop = (intVertical - sVertical) /2
        Window.moveTo intLeft, intTop
        '# default window content
        window.location.href="#Top"
      End Sub
      
      
      Sub RunScript
      on Error Resume Next
      
      ' *** variables
      mDrive = "K:"
      strRemoteShare = "\\server\share"
      strDriveAlias = "share name"
      
      strUPNsuffix = "@domain.com"
      
      minUSRnamelength = 2
      minPASSwrdlength = 3
      
      
      ' *** Map drive using the entered credentials
      
      strUsr = UsrnameArea.Value
      strPas = PasswordArea.Value
      
      Set objNetwork = CreateObject("WScript.Network")
      Set oShell = CreateObject("Shell.Application")
      
       If Len(strUsr) >= minUSRnamelength then
           strUsr = Ucase(strUsr) & strUPNsuffix  '<--- adds the UPNsuffix to the account
      
            if Len(strPas) >= minPASSwrdlength then
               Err.Clear
               objNetwork.MapNetworkDrive mDrive, strRemoteShare, False, strUsr, strPas
                If Err.Number = 0 Then
                   oShell.NameSpace(mDrive).Self.Name = strDriveAlias
                End If
             ELSE 
                Msgbox chr(34) & strPas & """  is an incorrect password !"
                Exit Sub
             End If
       ELSE 
          Msgbox chr(34) & strUsr & """  is an incorrect Username !"
          Exit Sub
       End If
      
      Set oShell = Nothing
      Set objNetwork = Nothing
         Self.Close()
      End Sub
      
      
      Sub CancelScript
         Set oShell = Nothing
         Set objNetwork = Nothing
         Self.Close()
      End Sub
      
      </SCRIPT>
      
      
      <BODY STYLE="font:14 pt arial; color:white; filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=1, StartColorStr='#000000', EndColorStr='#0000FF')">
      <a name="Top"></a><CENTER>
        <table border="0" cellpadding="0" cellspacing="0"><font size="2" color="black" face="Arial">
          <tr>
            <td height="30">
              <p align="right">Your Username</p>
            </td>
            <td height="30">&nbsp;&nbsp; <input type="text" name="UsrnameArea" size="30"></td></tr>
          <tr>
            <td height="30">
              <p align="right">@domain.com Password</p>
            </td>
            <td height="30">&nbsp;&nbsp; <input type="password" name="PasswordArea" size="30"></td></tr>
        </table><BR>
      <HR color="#0000FF">
       <Input id=runbutton class="button" type="button" value="      Create Drive      " name="run_button"  onClick="RunScript">
          &nbsp;&nbsp;&nbsp; 
       <Input id=runbutton class="button" type="button" value="Cancel" name="cancel_button"  onClick="CancelScript">
      </CENTER>
      </BODY>
      
      </HTML>
      (Open Notebook.exe Copy and paste the code above. Save the file as "MappingWithCredentials.HTA", or any other name for the HTA-file)

      The vbscript part of the file is in Blue so you can easily see that there is almoste no difference between the previous vbs-file.
      But note that HTA not is runned like vbscripts with wscript.exe or cscript.exe, but HTA is runned by mshta.exe. Therefore you can not use all of the same wscript code in HTA. That is why you also see often that a real vbs-file is used as main part for the scripting and it calls HTML-files for its 'graphical user interfaces'.

      To edit the HTA-file rightclick on it and choose 'open with' --> 'notepad'.
      lots more on HTA


      note,
      The scipts adds the @UPNsuffix to the entered username. But,, the AD Accountname and the NT Account names does not have to be the same!!! So Instead of the "@UPNsuffix" (user's PrincipalName) you might want to use the "nbdomain\" prefix (user's sAMAccountName).



      \Rems
      Last edited by Rems; 20th October 2008, 21:00.

      This posting is provided "AS IS" with no warranties, and confers no rights.

      __________________

      ** Remember to give credit where credit's due **
      and leave Reputation Points for meaningful posts

      Comment


      • #4
        Re: VBScript mapping a drive with a username and password

        WOW you guys are awesome!! thanks for the information. I am a noob at scripting so I got a book on it as well. I will use this to come up with the kind of script I am looking for.

        Thanks alot!!!!

        Comment


        • #5
          Re: VBScript mapping a drive with a username and password

          This is some cool stuff...how would you get the application to close after you know the drive has mapped?

          Comment


          • #6
            Re: VBScript mapping a drive with a username and password

            Hmmm 1 issue I am having with this, is that "mshta.exe" does not seem to close when I close out of the script. I see that the process is still running and I have to kill it manually.

            Comment


            • #7
              Re: VBScript mapping a drive with a username and password

              Do vbs functions not work in hta?

              Comment


              • #8
                Re: VBScript mapping a drive with a username and password

                Hi ekrengel,

                Yes most vbs functions will work in HTA.
                But the ones opening with the word "wscript." are not supported.

                Did you found out why "mshta.exe" did not close?
                I think it must be because of a script crash, - or you ran the script on a terminalserver that was not the latest updates installed?



                With HTA you can create realy nice user interfaces.
                If you like to use icons and images in the lay-out, it is best to use 'relative path' to these objects. Place them all in the same directory.
                Then you can use WinRAR to create an Advanced SFX file (= self extracting exe-file), that can extract silent , hidden and can auto execute the HTA if you select it at "run program after extraction". This way you can create a standalone application.


                \Rems

                This posting is provided "AS IS" with no warranties, and confers no rights.

                __________________

                ** Remember to give credit where credit's due **
                and leave Reputation Points for meaningful posts

                Comment


                • #9
                  Re: VBScript mapping a drive with a username and password

                  Hi Rems,

                  Yes they do work with HTA, I didn't realize I had the function in one of my subs that it should have been outside of...as for mshta not closing, I'm still not sure about that. I guess I don't have the script completly done yet so there are probabaly some more errors I'm not catching. Thank you for giving me more information on the sfx file, I will most likely try that too.

                  Comment


                  • #10
                    Re: VBScript mapping a drive with a username and password

                    this script map a drive to a server in a different domain. Works great when user corresponds to user logged into Windows. When the username/password is different get error message "credentials supplied conflict with an existing set of credentials". Is there a way to perform the mapping without the O/S verifying against the CID for the current windows user?

                    /rc

                    ================================================== ======

                    Option Explicit

                    Dim objNetwork, objShell, objExp
                    Dim objFSO, objFileCopy
                    Dim strMapDriveLetter, strMapDrivePath, strUserName, strPassword, bUpdateProfile
                    Dim strSourceLetter, strSourcePath, strFullSource
                    Dim strTargetLetter, strTargetPath, strFullTargetPath, strFullTarget
                    Dim CheckDrive, AlreadyConnected, intDrive

                    Set objNetwork = CreateObject("WScript.Network")
                    Set objShell = CreateObject("WScript.Shell")
                    Set objFSO = CreateObject("Scripting.FileSystemObject")
                    Set CheckDrive = objNetwork.EnumNetworkDrives()


                    ' Init variables
                    ' --------------

                    'set drive letter to map
                    strMapDriveLetter = "m:"

                    'map drive to this path
                    strMapDrivePath = "\\servername\sharename"


                    'set security info
                    strUserName = "domainname\username"
                    strPassword = "userpassword"
                    bUpdateProfile = "false"


                    ' Run procedure
                    ' -------------

                    'check if network drives already exist and remove
                    Call DeleteDrive

                    'map network drives
                    objNetwork.MapNetworkDrive strMapDriveLetter, strMapDrivePath, bUpdateProfile, strUserName, strPassword

                    ' Calls subroutine to check if drive is already connected
                    'call Explorer


                    'WSCript.Echo "End Script"
                    WScript.Quit


                    Sub DeleteDrive()
                    On Error Resume Next
                    AlreadyConnected = False

                    'For intDrive = 0 To CheckDrive.Count - 1 Step 2
                    For intDrive = 0 To CheckDrive.Count
                    If CheckDrive.Item(intDrive) =strMapDriveLetter Then AlreadyConnected =True
                    Next

                    If AlreadyConnected = True then
                    objNetwork.RemoveNetworkDrive strMapDriveLetter, True, True
                    'Msgbox "Drive Deleted"
                    End if
                    End Sub

                    sub Explorer()
                    set objExp = CreateObject("WScript.Shell")
                    objExp.Run ("Explorer" & " " & strMapDriveLetter )
                    End Sub

                    Comment

                    Working...
                    X