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"

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    = "无法添加打印机驱动程序"

CreateNewPrinterName


'
' AddPrinter execution starts here
sub CreateNewPrinterName

    dim iRetval
    dim strPrinterName  
    dim objWMIService
    dim objPrinter
    Dim colInstalledPrinters 
	Dim intMaxPrinterNumber
	Dim strTempPrinterNumber
	dim strOnePrinterName
	Dim intPosi
	dim intPosi1
	dim strNPN

    strPrinterName   = "HPRT"
    

	if ReadPrinterName(strNPN) then
		strPrinterName=strNPN			
	
		Set objWMIService = GetObject("Winmgmts:")  
		objWMIService.Security_.Privileges.AddAsString "SeLoadDriverPrivilege", True 
		
		Set colInstalledPrinters =  objWMIService.ExecQuery("Select * from Win32_Printer Where Name like '"+strPrinterName+"%'")				
		'**********处理打印机重名问题
		intMaxPrinterNumber=0
		Set colInstalledPrinters =  objWMIService.ExecQuery _ 
			("Select * from Win32_Printer Where Name = '"+strPrinterName+"' or Name like '"+strPrinterName+"(%'")	
		'找出当前型号的所有打印机
		If colInstalledPrinters.count=1 Then
			intMaxPrinterNumber=1
			For Each objPrinter in colInstalledPrinters			
				strOnePrinterName=objPrinter.DeviceID
			Next	
		else			
			For Each objPrinter in colInstalledPrinters			
				intPosi=InStr(objPrinter.DeviceID,"(")
				intPosi1=InStrRev(objPrinter.DeviceID,")")
				If intPosi>0 Then
					strTempPrinterNumber=mid(objPrinter.DeviceID,intPosi+1,intPosi1-intPosi-1)				
					'获取最大索引值.如：MPT-II(3)中的3
					If (left(strTempPrinterNumber,1)>="0" and left(strTempPrinterNumber,1)<="9") Then
						if (cint(strTempPrinterNumber)>intMaxPrinterNumber) then
							intMaxPrinterNumber=strTempPrinterNumber
						end if
					End if
				End if
			Next					
		End if

		'生成新的打印机名称		
		If (colInstalledPrinters.count=1) and instr(strOnePrinterName,"(USB)")=0 Then
			strPrinterName=strPrinterName & "(" & cint(intMaxPrinterNumber) & ")"	
		else
			if colInstalledPrinters.count>0	then
				strPrinterName=strPrinterName & "(" & cint(intMaxPrinterNumber+1) & ")"
			end if
		end if			
		'**********处理打印机重名问题

		WritePrinterNameToFiles(strPrinterName)

		
    end if

End Sub

'
' Parse the command line into its components
'
function ParseCommandLine(strPrinterName)

    on error resume next

'    DebugPrint kDebugTrace, L_Text_Dbg_Msg05_Text

    dim oArgs
    dim iIndex

    iIndex = 0
    set oArgs = wscript.Arguments

    while iIndex < oArgs.Count
        select case oArgs(iIndex)
            case "-d"
                iIndex = iIndex + 1
                strPrinterName= oArgs(iIndex)  
         
            case else                
                exit function
        end select
        iIndex = iIndex + 1
    wend

    if Err.Number <> 0 then
        ParseCommandLine = kErrorFailure
    else
        ParseCommandLine = kErrorSuccess
    end if

end  function

function WritePrinterNameToFiles(strPrinterName)
dim fso
dim f
dim ForWriting
dim content

    ForWriting=2
    set fso = CreateObject("Scripting.FileSystemObject")
    set f = fso.OpenTextFile("NewPrinterName.ini",ForWriting)

    f.Write strPrinterName
    f.close()

    if Err.Number <> 0 then        
        WritePrinterNameToFiles = false
    else
        WritePrinterNameToFiles = 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("DriverName.ini",ForReading)
    strPrinterName=f.ReadLine()    
    f.close()

    if Err.Number <> 0 then
        
        ReadPrinterName = false
    else
        ReadPrinterName = true
    end if
end function

'
' 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
