option explicit

'
' Debugging trace flags, to enable debug output trace message
' change gDebugFlag to true.
'
const kDebugTrace = 1
const kDebugError = 2
dim gDebugFlag

gDebugFlag = false

'
' Operation action values.
'
const kErrorSuccess     = 0
const kErrorFailure     = 1

const kNameSpace        = "root\cimv2"

'
' Generic strings
'
const L_Empty_Text                 = ""
const L_Space_Text                 = " "
const L_Error_Text                 = "错误"
const L_Success_Text               = "成功"
const L_Failed_Text                = "失败"
const L_Hex_Text                   = "0x"
const L_Printer_Text               = "打印机"
const L_Operation_Text             = "操作"
const L_Provider_Text              = "提供程序"
const L_Description_Text           = "描述"
const L_Debug_Text                 = "调试:"

const L_Help_Help_General01_Text   = "用法: CScript InstallPrinter.vbs [-d printer name] [-p port mame] [-i inf file] "
const L_Help_Help_General02_Text   = "              [-h path] [-m model] [-e environment] [-v version]"
const L_Help_Help_General03_Text   = "参数:"
const L_Help_Help_General04_Text   = "-d     - 指定添加的打印机名称"
const L_Help_Help_General05_Text   = "-p     - 端口名称"
const L_Help_Help_General06_Text   = "-m     - 驱动程序型号名"
const L_Help_Help_General07_Text   = "-h     - 驱动程序文件路径"
const L_Help_Help_General08_Text   = "-i     - 完全合格的 inf 文件名"
const L_Help_Help_General09_Text   = "-e     - 环境 ""Windows {NT x86 | X64 | IA64}"""
const L_Help_Help_General10_Text   = "-v     - 版本"
const L_Help_Help_General11_Text   = "-?     - 显示命令用法"
const L_Help_Help_General12_Text   = "例如:"
const L_Help_Help_General13_Text   = "CScript InstallPrinter.vbs -d Printer1 -p COM1: -i ""D:\DT-230\PT950.inf"""
const L_Help_Help_General14_Text   = "CScript InstallPrinter.vbs  -d Printer1 -p COM1: -i ""D:\DT-230\PT950.inf"" -v 3 -e ""Windows NT x86"""
const L_Help_Help_General15_Text   = "CScript InstallPrinter.vbs  -d Printer1 -p COM1: -m ""DT-230 Printer Driver"" -i ""D:\DT-230\PT950.inf"" -p ""D:\DT-230"" -v 3 -e ""Windows x64"""
const L_Help_Help_General16_Text   = "备注:"
const L_Help_Help_General17_Text   = "inf 文件名必须完全合格。"

'
' Messages to be displayed if the scripting host is not cscript
'
const L_Help_Help_Host01_Text      = "此脚本应该用 CSCRIPT.EXE 在命令提示符下执行。"
const L_Help_Help_Host02_Text      = "例如: CScript script.vbs 参数"
const L_Help_Help_Host03_Text      = ""
const L_Help_Help_Host04_Text      = "要设置 CScript 作为运行 .vbs 文件的默认应用程序，运行如下:"
const L_Help_Help_Host05_Text      = "     CScript //H:CScript //S"
const L_Help_Help_Host06_Text      = "然后可以运行 ""script.vbs arguments""，而无需在运行脚本前先使用 CScript。"

'
' Miscellaneous messages
'
const L_Text_Msg_General01_Text    = "已添加打印机驱动程序"
const L_Text_Msg_General02_Text    = "无法添加打印机驱动程序"


AddPrinter


'
' AddPrinter execution starts here
sub AddPrinter
    dim iRetval
    dim strComputer
    dim strPrinterName
    dim strPortName
    dim strInfFile
    dim strModel
    dim strPath
    dim uVersion
    dim strEnvironment
    dim WshShell 
    dim strAddPrinterDriverCMD
    dim objWMIService
    dim objPrinter
    dim  intResult
	Dim colInstalledPrinters 
	Dim intMaxPrinterNumber
	Dim strTempPrinterNumber
	dim strOnePrinterName
	Dim intPosi
	dim intPosi1
	dim IsDefaultPrinter
	Dim starttime
	dim strNPN

    strComputer = "."
    strPrinterName   = "PRTPrinter8"
    strPortName   = "COM1:"
    strModel= "HPRT TP806" 
    strInfFile="D:\PT950.inf"
    strPath=""
    uVersion=""
    strEnvironment=""
    iRetval=0
    IsDefaultPrinter="1"

    '
    ' Abort if the host is not cscript
    '
    if not IsHostCscript() then

        call wscript.echo(L_Help_Help_Host01_Text & vbCRLF & L_Help_Help_Host02_Text & vbCRLF & _
                          L_Help_Help_Host03_Text & vbCRLF & L_Help_Help_Host04_Text & vbCRLF & _
                          L_Help_Help_Host05_Text & vbCRLF & L_Help_Help_Host06_Text & vbCRLF)

        wscript.quit

    end if

    '
    ' Get command line parameters
    '
    iRetval = ParseCommandLine(strPrinterName, strPortName, strModel, strInfFile, strPath, uVersion, strEnvironment,IsDefaultPrinter)

    if iRetval = kErrorSuccess  then
        Set WshShell = Wscript.CreateObject("Wscript.Shell")
    
        strAddPrinterDriverCMD="rundll32 printui.dll,PrintUIEntry /ia /m "  & """" & strModel  & """" & " /f " & """" & strInfFile & """"
        if strPath<>"" then
            strAddPrinterDriverCMD= strAddPrinterDriverCMD & " -h "  & """" & strPath  & """"
        end if
        if uVersion<>"" then
            strAddPrinterDriverCMD= strAddPrinterDriverCMD & " -v "  & """" & uVersion  & """"
        end if
        if strEnvironment<>"" then
            strAddPrinterDriverCMD= strAddPrinterDriverCMD & " -e "  & """" & strEnvironment  & """"
        end if	

	wscript.echo strAddPrinterDriverCMD
        WshShell.Run strAddPrinterDriverCMD,1,True   
	wscript.echo strPrinterName
	
        'WshShell.Run "wscript.exe CreateNewPrinterName.vbs -d" & strPrinterName,1,True
	createobject("wscript.shell").run "CreateNewPrinterName.vbs -d """ & strPrinterName & """ ,0"
	wscript.echo "CreateNewPrinterName.vbs -d """ & strPrinterName & """ ,0"

  	starttime = Timer
  	Do Until (Timer - starttime) > 1
  		intPosi = Timer		
  	Loop

	if ReadPrinterName(strNPN) then
		strPrinterName=strNPN
		wscript.echo strPrinterName		
	end if

        'Create a new printer 
	Set objWMIService = GetObject("Winmgmts:")  
    	objWMIService.Security_.Privileges.AddAsString "SeLoadDriverPrivilege", True
        Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
        objPrinter.DriverName = strModel
        objPrinter.PortName   = strPortName
        objPrinter.DeviceID   = strPrinterName
        objPrinter.Network = false
        objPrinter.Shared = false
        intResult= objPrinter.Put_

	if IsDefaultPrinter="1" then
		strAddPrinterDriverCMD="rundll32 printui.dll,PrintUIEntry /y /n " & """" & strPrinterName  & """"
		WshShell.Run strAddPrinterDriverCMD,1,True
	end if

	if Err.Number <> 0 then
        	wscript.echo L_Text_Msg_General02_Text & vbCRLF & Err.Description
	else 
        	wscript.echo L_Text_Msg_General01_Text
	end if
    end if

End Sub

'
' Parse the command line into its components
'
function ParseCommandLine(strPrinterName,strPortName,strModel, strInfFile, strPath, uVersion, strEnvironment,IsDefaultPrinter)

    on error resume next

'    DebugPrint kDebugTrace, L_Text_Dbg_Msg05_Text

    dim oArgs
    dim iIndex
    dim line1,line2,line3,line4

    iIndex = 0

    set oArgs = wscript.Arguments

    while iIndex < oArgs.Count

        select case oArgs(iIndex)
            case "-d"
                iIndex = iIndex + 1
                strPrinterName= oArgs(iIndex)

            case "-p"
                iIndex = iIndex + 1
                strPortName = oArgs(iIndex)

            case "-m"
                iIndex = iIndex + 1
                strModel = oArgs(iIndex)

            case "-h"
                iIndex = iIndex + 1
                strPath = oArgs(iIndex)

            case "-v"
                iIndex = iIndex + 1
                uVersion = oArgs(iIndex)

            case "-e"
                iIndex = iIndex + 1
                strEnvironment = oArgs(iIndex)

            case "-i"
                iIndex = iIndex + 1
                strInfFile = oArgs(iIndex)

            case "-f"
                iIndex = iIndex + 1
                if(ReadContentsFromFiles(oArgs(iIndex),line1,line2,line3,line4)) Then
			strModel=line2
                    	strPrinterName=line1
                    	strPortName=line3
			IsDefaultPrinter=line4		
                end if

            case "-?"
                Usage(true)
                exit function

            case else
                Usage(true)
                exit function

        end select

        iIndex = iIndex + 1

    wend

    if Err.Number <> 0 then

        wscript.echo "ParseCommandLine Error:" & Err.Description

        ParseCommandLine = kErrorFailure
    else
        ParseCommandLine = kErrorSuccess
    end if

end  function

function ReadContentsFromFiles(fileName,line1,line2,line3,line4)
dim fso
dim f
dim forReading
dim content

    forReading=1
    set fso = CreateObject("Scripting.FileSystemObject")
    set f = fso.OpenTextFile(fileName,forReading)

'    '读取文件的内容
    line1=f.ReadLine()
    line2=f.ReadLine()
    line3=f.ReadLine()
    line4=f.ReadLine()
    f.close()

    if Err.Number <> 0 then
        wscript.echo "ReadContentsFromFiles Error:" & Err.Description
        ReadContentsFromFiles = false
    else
        ReadContentsFromFiles = true
    end if
end function

function ReadPrinterName(strPrinterName)
dim fso
dim f
dim ForReading
dim content

    ForReading=1
    set fso = CreateObject("Scripting.FileSystemObject")
    set f = fso.OpenTextFile("NewPrinterName.ini",ForReading)
    strPrinterName=f.ReadLine()
    
    f.close()

    if Err.Number <> 0 then
        wscript.echo "ReadPrinterName Error:" & Err.Description
        ReadPrinterName = false
    else
        ReadPrinterName = true
    end if
end function

'
' Display command usage.
'
sub Usage(bExit)

    wscript.echo L_Help_Help_General01_Text
    wscript.echo L_Help_Help_General02_Text
    wscript.echo L_Help_Help_General03_Text
    wscript.echo L_Help_Help_General04_Text
    wscript.echo L_Help_Help_General05_Text
    wscript.echo L_Help_Help_General06_Text
    wscript.echo L_Help_Help_General07_Text
    wscript.echo L_Help_Help_General08_Text
    wscript.echo L_Help_Help_General09_Text
    wscript.echo L_Help_Help_General10_Text
    wscript.echo L_Help_Help_General11_Text
    wscript.echo L_Help_Help_General12_Text
    wscript.echo L_Help_Help_General13_Text
    wscript.echo L_Help_Help_General14_Text
    wscript.echo L_Help_Help_General15_Text
    wscript.echo L_Help_Help_General16_Text
    wscript.echo L_Help_Help_General17_Text


    if bExit then

        wscript.quit(1)

    end if

end sub


'
' Determines which program is being used to run this script.
' Returns true if the script host is cscript.exe
'
function IsHostCscript()

    on error resume next

    dim strFullName
    dim strCommand
    dim i, j
    dim bReturn

    bReturn = false

    strFullName = WScript.FullName

    i = InStr(1, strFullName, ".exe", 1)

    if i <> 0 then

        j = InStrRev(strFullName, "\", i, 1)

        if j <> 0 then

            strCommand = Mid(strFullName, j+1, i-j-1)

            if LCase(strCommand) = "cscript" then

                bReturn = true

            end if

        end if

    end if

    if Err <> 0 then

        wscript.echo L_Text_Error_General01_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                     & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description

    end if

    IsHostCscript = bReturn

end function
