Script to set default printer

I'd like to create a script or .hta to allow my users to easily change their default printer. So far I have this below.

<SCRIPT Language="VBScript">

    Sub Window_Onload
        strComputer = "."

        Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
        Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")

        For Each objPrinter in colPrinters
            strPrinter = objPrinter.Name
            Set objOption = Document.createElement("OPTION")
            objOption.Text = strprinter
            objOption.Value = strPrinter
    End Sub

    Sub SetDefault
        strPrinter = AvailablePrinters.Value
        Set WshNetwork = CreateObject("Wscript.Network")
        WshNetwork.SetDefaultPrinter strPrinter
        Msgbox strprinter & " has been set as your default printer."
    End Sub


<select size="5" name="AvailablePrinters"></select><p>
<input type="button" value="Set as Default" onClick="SetDefault">

When I run it to test I get this:

Who is Participating?
I was looking at this one earlier:

One thing that's nice (in a way) is that you're actually having a line fail.  So if we can just see which line is bombing we should be able to troubleshoot it.

What I would do since your script is pretty small would be to add a few message boxes in your code so you can see the last one to pop up and what the value of strPrinter is.  Then when it does fail, you can see what code comes after the last message box that you saw when you ran the script.  So intersperse some lines like:  Msgbox("Position 1"), Msgbox("Position 2"), etc. in your code.  If you're failing when you hit the Submit button, it's the SetDefault function we should look at.  See the attached code for what I'd suggest you test with:
    Sub SetDefault
        strPrinter = AvailablePrinters.Value
        Msgbox "The value of strPrinter is: " & strPrinter
        Set WshNetwork = CreateObject("Wscript.Network")
        Msgbox "WshNetwork created"
        WshNetwork.SetDefaultPrinter strPrinter
        Msgbox strprinter & " has been set as your default printer."
    End Sub

Open in new window

Does strPrinter contain the server name as well as the printer name?  I know that SetDefaultPrinter is going to want "\\servername\printername".

Do you know the exact statement that is failing?  If not... Can you throw some message boxes in there to help determine where exactly in the script it is failing?
mhmservicesAuthor Commented:

I'm trying to follow the example above. The thing you have to remember is I'm not versed in scripting so I'm finding it difficult to follow.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.