Map a printer using an HTA script

Good day all,
My goal  is to map a printer to laptop that is not part of the domain.
To log into the server and map the printer requires two files which is a problem because, the first file get username and password for the server, but can’t run second vbs file because the laptop doesn’t know the server account.

I found an HTA script that maps a drive to the server in question which has a logon, this works pretty good. (forces logon as domain user)

I need to include in that HTA file a simple way to map the printer and delete the map drive, I’ve tried copying a vsscript code but results in errors.  Hope someone can help with this.
Regards.


Here is the code – I have the vbScript marked second scrip starts(ends) here.

<HTML>
<HEAD>
<TITLE>Setup Printers</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 = "Q:"
strRemoteShare = "\\bafps02\tmpShare$"
'strDriveAlias = "tmpShare$"

strUPNsuffix = "@dmi.rossu.loc"

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
      msgBox("Drive should be mapped")
             '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


WScript.sleep 100000
objNetwork.RemoveNetworkDrive mDrive, strRemoteShare, False, strUsr, strPas

msgBox("Drive removed")


'***************************Second script starts **************
On Error Resume Next



Dim strTarget, strPingResults
strTarget = "bafps02"  ' could be host name or IP address

'Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshExec = WshShell.Exec("ping -n 2 -w 2000 " & strTarget)' send 2 echo request, waiting 2secs each
strPingResults = LCase(WshExec.StdOut.ReadAll)

If InStr(strPingResults, "reply from") Then
      SetPrinters
Else
      msgBox ("Make sure you are connected to the network before running script, thanks")
End If



Sub SetPrinters()

' Set printers
' ******************************
On Error Resume Next

Dim objNetwork
Dim prtCanon
Dim prtLRC
Dim myPrinter

Set objNetwork = CreateObject("WScript.Network")

prtCanon = "\\bafps02\Papercut_Canon"
prtLRC = "\\bafps02\LRC_Printer"

'objNetwork.RemoveWindowsPrinterConnection ' .prtCanon
'objNetwork.RemoveWindowsPrinterConnection ' .prtLRC

'To delay 10 seconds try this
' WScript.sleep 10000

objNetwork.AddWindowsPrinterConnection.prtCanon  
msgBox ("Installing " & prtCanon)

WScript.sleep 15000

objNetwork.AddWindowsPrinterConnection.prtLRC            
msgBox ("Installing " & prtLRC)

'objNetwork.AddWindowsPrinterConnection "\\server\printer3"
'objNetwork.AddWindowsPrinterConnection "\\server\printer4"
'objNetwork.AddWindowsPrinterConnection "\\server\printer5"

WScript.sleep 15000



msgBox "Please wait, Checking Printer(s)"

myPrinter = Printer.prtCanon
If Err.Number Then
      msgBox ("printer " & prtCanon & " did not install")
Else
      msgBox ("Printer " & prtCanon & " installed ok!")
End If


myPrinter = Printer.prtLRC
If Err.Number Then
      msgBox ("printer " & prtLRC & " did not install")
      msgBox ("Make you are logged into the network")
Else
      msgBox ("Printer " & prtLRC & " installed ok!")
            objNetworkSetDefaultPrinter.prtCanon

End If

End Sub




'*****************************second script ends ***********
msgBox("script ended")

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>
mjlarodaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ben Personick (Previously QCubed)Lead Network EngineerCommented:
You could just use batch/cmd instead if you can call that from whatever language HTA is.

NET USE [Drive-Letter]: "\\[UNC\PATH]" -User:"Domain\Username" "[Password]"
0
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
You could just use batch/cmd instead if you can call that from whatever language HTA is.

NET USE [Drive-Letter]: "\\[UNC\PATH]" -User:"Domain\Username" "[Password]"
0
RobSampsonCommented:
Hi, the only way I can see to map printers using alternate credentials is to first use CmdKey.exe to add credentials (via the password manager) for a specific resource, namely your bafps02 server, and then connect the printers.

Replace this section
objNetwork.AddWindowsPrinterConnection.prtCanon   
msgBox ("Installing " & prtCanon)

WScript.sleep 15000

objNetwork.AddWindowsPrinterConnection.prtLRC
msgBox ("Installing " & prtLRC)

Open in new window


with this:
strServer = "bafps02"
strCommand = "cmd /c cmdkey /add:" & strServer & " /user:" & UsrnameArea.Value & " /pass:" & PasswordArea.Value
 
Set objShell = CreateObject("WScript.Shell")
objShell.Run strCommand, 0, True
 
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection prtCanon
objNetwork.AddWindowsPrinterConnection prtLRC
 
strResponse = MsgBox("Do you want to remove the cached credentials for " & strServer & "?", vbYesNo, "Remove Cached Credentials")
If strResponse = vbYes Then objShell.Run "cmd /c cmdkey " & strServer & " /delete", 0, True

Open in new window


and see if that helps.

Regards,

Rob.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

mjlarodaAuthor Commented:
Wow it’s working; I had to delete all that other stuff from the second script area to stop the errors.  Thanks a lot, now I could present more professional.
0
mjlarodaAuthor Commented:
Wow it’s working; I had to delete all that other stuff from the second script area to stop the errors.  Thanks a lot, now I could present more professional.
0
RobSampsonCommented:
No problem. Thanks for the grade.

Rob.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.