Board logo

标题: [其他] 批处理如何安装网络打印机 [打印本页]

作者: 飛雪    时间: 2014-4-24 17:49     标题: 批处理如何安装网络打印机

本帖最后由 pcl_test 于 2016-7-13 00:22 编辑

因單位有大量的XP、7機器有此需求

還要勞煩前輩指教了

感激不盡...
作者: yu2n    时间: 2014-4-24 20:43

这是我正在用的,驱动共享路径、IP端口等需要自己按实际情况修改
  1. ' ====================================================================================================
  2. Dim WhoAmI, TmpDir, WinDir, AppDataDir, MeDir :    Call GetGloVar()    ' 初始化全局变量
  3. ' 加密自身
  4. Call MeEncoder()
  5. ' 重复运行则退出
  6. If MeIsAlreadyRun() = True Then WScript.Quit
  7. ' 非XP系统退出
  8. If Not LCase(OSVer()) = "xp" Then WScript.Quit
  9. ' 是否映射网络
  10. If Not Exist(strDriverPath & "") Then
  11. ErrorInfo "错误:不能连接网络驱动器", "找不到 \\texdgntf\div$\PRINT ! 请连接后重试!", 3
  12. WScript.Quit
  13. End If
  14. ' 取消安装未签名驱动的提示,安装时忽略未签名的驱动程序
  15. Call DriverSigningIagree()
  16. ' 取得当前打印机列表
  17. PrintList_1 = ShowPrint(".")
  18. ' ====================================================================================================
  19. ' vbs脚本自动安装打印机
  20. '-------------------------------------------------------------------------------'
  21. '--------------------------查看和添加远程网络打印机-----------------------------'
  22. '   注意:需要有对方管理员权限'
  23. '-------------------------------------------------------------------------------'
  24. ' strComputer = InputBox("PC NAME 你要添加打印机的电脑的名称")
  25. strComputer = "."
  26. strDriverPath = "\\server03\driver$\print"
  27. ' 添加驱动
  28. add_driver strComputer, "HP LaserJet 2200 Series PCL 6", strDriverPath & "\HP2200\WIN2000\PCL6", strDriverPath & "\HP2200\WIN2000\PCL6\HPBF322I.INF"
  29. add_driver strComputer, "HP LaserJet 2300 Series PCL 6", strDriverPath & "\HP2300", strDriverPath & "\HP2300\hpc2300c.inf"
  30. 'add_driver strComputer, "hp LaserJet 1320 PCL 6", strDriverPath & "\HP1320\HP_LJ1320_PCL6_Driver", strDriverPath & "\HP1320\HP_LJ1320_PCL6_Driver\hpc1320c.inf"
  31. 'add_driver strComputer, "HP LaserJet 4350 PCL 6", strDriverPath & "\HP4350\HP4350_PCL6_Driver", strDriverPath & "\HP4350\HP4350_PCL6_Driver\hpc4x50c.inf"
  32. ' 添加端口
  33. add_port strComputer, "192.168.118.233"
  34. add_port strComputer, "192.168.118.234"
  35. add_port strComputer, "192.168.118.235"
  36. add_port strComputer, "192.168.118.236"
  37. add_port strComputer, "192.168.118.237"
  38. ' 添加打印机
  39. add_print_local "Epson LQ-2500C", "LPT1:", "Epson LQ-1170 ESC/P 2"
  40. add_print_lcoal_inf "hp LaserJet 1320 PCL 6", strDriverPath & "\HP1320\HP_LJ1320_PCL6_Driver\hpc1320c.inf", "LPT1:", "hp LaserJet 1320 PCL 6"
  41. add_print_lcoal_inf "HP LaserJet 4350 PCL 6", strDriverPath & "\HP4350\HP4350_PCL6_Driver\hpc4x50c.inf", "LPT1:", "HP LaserJet 4350 PCL 6"
  42. 'add_print strComputer, "HP LaserJet 2200 Series PCL 6", "LPT1:", "vdy4_laser", "工艺组"
  43. add_print strComputer, "HP LaserJet 2200 Series PCL 6", "LPT1:", "vdy4_laser", ""
  44. add_print strComputer, "HP LaserJet 2200 Series PCL 6", "LPT1:", "job_laser", ""
  45. add_print strComputer, "HP LaserJet 2200 Series PCL 6", "LPT1:", "HP LaserJet 2200 Series PCL 6", ""
  46. add_print strComputer, "HP LaserJet 2300 Series PCL 6", "LPT1:", "HP LaserJet 2300 Series PCL 6", ""
  47. ' 恢复安装未签名驱动的提示,安装时提示未签名的驱动程序
  48. Call DriverSigningWarning()
  49. ' 显示完成信息
  50. PrintList_2 = ShowPrint( "." )
  51. If PrintList_1 <> "" Then
  52. PrintList_1_arr = Split( PrintList_1, VbCrLf, -1, 1)
  53. PrintList_2_arr = Split( PrintList_2, VbCrLf, -1, 1)
  54. For I = 0 To UBound( PrintList_2_arr )
  55. For J = 0 To UBound( PrintList_1_arr )
  56. If PrintList_2_arr( I ) = PrintList_1_arr( J ) Then
  57. PrintList_2_arr( I ) = ""
  58. Exit For
  59. End If
  60. Next
  61. Next
  62. For I = 0 To UBound( PrintList_2_arr )
  63. If PrintList_2_arr( I ) <> "" Then ChangePrintList = ChangePrintList & VbCrLf & PrintList_2_arr( I )
  64. Next
  65. 'ChangePrintList = Join( PrintList_2_arr, VbCrLf )
  66. 'ChangePrintList = ReplaceTest( ChangePrintList, "\s*", VbCrLf )
  67. Else
  68. ChangePrintList = PrintList_2
  69. End If
  70. TipInfo "提示:安装完成", ChangePrintList, 30
  71. WScript.Quit
  72. ' ====================================================================================================
  73. '添加驱动。不支持2000以下下操作系统。包括2000
  74. Sub add_driver( strComputer, DriverName, DriverFolderPath, DriverConfigFilePath )
  75. Set shell = WScript.createObject("wscript.shell")
  76. shell.run "cmd.exe /c cscript %windir%\system32\prndrvr.vbs -a -m """ & DriverName & """ -s " & strComputer & " -h """ & DriverFolderPath & """ -i """ & DriverConfigFilePath & """", 0, true
  77. Set shell = Nothing
  78. End Sub
  79. ' ====================================================================================================
  80. '添加端口'
  81. Sub add_port( strComputer, strIPAddress )
  82. On Error Resume Next
  83. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(LoadDriver)}!\\" & strComputer & "\root\cimv2")
  84. Set objNewPort = objWMIService.Get("Win32_TCPIPPrinterPort").SpawnInstance_
  85. objNewPort.Name = "IP_" & strIPAddress
  86. objNewPort.Protocol = 1
  87. objNewPort.HostAddress = strIPAddress
  88. objNewPort.PortNumber = "9100"
  89. objNewPort.SNMPEnabled = False
  90. objNewPort.SNMPCommunity = "Public"
  91. objNewPort.Put_
  92. Set objNewPort = Nothing
  93. Set objWMIService = Nothing
  94. End Sub
  95. ' ====================================================================================================
  96. '添加打印机
  97. Sub add_print( strComputer, DriverName, PortName, PrintName, Location )
  98. On Error Resume Next
  99. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(LoadDriver)}!\\" & strComputer & "\root\cimv2")
  100. Set objPrinter = objWMIService.Get("Win32_Printer").SpawnInstance_
  101. objPrinter.DriverName = DriverName
  102. objPrinter.PortName   = PortName
  103. objPrinter.DeviceID   = PrintName
  104. objPrinter.Location = Location
  105. objPrinter.Network = True
  106. objPrinter.Put_
  107. Set objPrinter = Nothing
  108. Set objWMIService = Nothing
  109. End Sub
  110. Sub add_print_local( DriverName, PortName, PrintName )
  111. On Error Resume Next
  112. Set shell = WScript.createObject("wscript.shell")
  113. shell.run "rundll32 printui.dll,PrintUIEntry /if /b """ & PrintName & """ /f """ & DriverConfigFilePath & """ /r """ & PortName & """ /m """ & DriverName & """ /z", 1, true
  114. Set shell = Nothing
  115. End Sub
  116. Sub add_print_lcoal_inf( DriverName, DriverConfigFilePath, PortName, PrintName )
  117. On Error Resume Next
  118. Set shell = WScript.createObject("wscript.shell")
  119. shell.run "rundll32 printui.dll,PrintUIEntry /if /b """ & PrintName & """ /f """ & DriverConfigFilePath & """ /r """ & PortName & """ /m """ & DriverName & """ /z", 1, true
  120. Set shell = Nothing
  121. End Sub
  122. ' ====================================================================================================
  123. '显示打印机
  124. Function ShowPrint( strComputer )
  125. On Error Resume Next
  126. Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(LoadDriver)}!\\" & strComputer & "\root\cimv2")
  127. Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Printer")
  128. For Each print_list in colItems
  129. ShowPrint = ShowPrint & print_list.DeviceID & VbCrLf
  130. Next
  131. Set colItems = Nothing
  132. Set objWMIService = Nothing
  133. End Function
  134. ' ====================================================================================================
  135. ' 安装时忽略未签名的驱动程序
  136. Sub DriverSigningIagree()
  137.     Set wso = WScript.CreateObject("WScript.Shell")
  138.     Sleep 200
  139.     Call RunNotWait( "rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,2" )
  140.     Do While i < 35    ' 在 7 秒内执行,35*200 = 7*1000
  141.         i = i + 1
  142.         If (AppActivate("系统属性") = True) Or (AppActivate("系統內容") = True) Then
  143.             Sleep 100
  144.             SendKeys "%S"
  145.             Sleep 100
  146.             If (AppActivate("驱动程序签名选项") = True) Or AppActivate("驅動程式碼簽署選項") = True Then
  147.                 Sleep 100
  148.                 SendKeys "%I"
  149.                 Sleep 100
  150.                 SendKeys "{ENTER}"
  151.                 Sleep 100
  152.                 SendKeys "{ESC}"
  153.                 Exit Do
  154.             Else
  155.                 SendKeys "{ESC}"
  156.             End If
  157.         End If
  158.         Sleep 200
  159.     Loop
  160.     Set wso = Nothing
  161. End Sub
  162. ' ====================================================================================================
  163. ' 安装时提示未签名的驱动程序
  164. Sub DriverSigningWarning()
  165.     Set wso = WScript.CreateObject("WScript.Shell")
  166.     Sleep 200
  167.     Call RunNotWait( "rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl,,2" )
  168.     Do While i < 35    ' 在 7 秒内执行,35*200 = 7*1000
  169.         i = i + 1
  170.         If (AppActivate("系统属性") = True) Or (AppActivate("系統內容") = True) Then
  171.             Sleep 100
  172.             SendKeys "%S"
  173.             Sleep 100
  174.             If (AppActivate("驱动程序签名选项") = True) Or AppActivate("驅動程式碼簽署選項") = True Then
  175.                 Sleep 100
  176.                 SendKeys "%W"
  177.                 Sleep 100
  178.                 SendKeys "{ENTER}"
  179.                 Sleep 100
  180.                 SendKeys "{ESC}"
  181.                 Exit Do
  182.             Else
  183.                 SendKeys "{ESC}"
  184.             End If
  185.         End If
  186.         Sleep 200
  187.     Loop
  188.     Set wso = Nothing
  189. End Sub
  190. ' ====================================================================================================
  191. ' ****************************************************************************************************
  192. ' *  公共函数
  193. ' *  使用方式:将本段全部代码加入程序末尾,将以下代码(1行)加入程序首行即可
  194. ' *            Dim WhoAmI, TmpDir, WinDir, AppDataDir, MeDir :   Call GetGloVar()   ' 初始化全局变量
  195. ' *  取得支持:电邮至 yu2n@qq.com
  196. ' *  更新日期:2012-11-30  11:35
  197. ' ****************************************************************************************************
  198. ' 功能索引
  199. ' 命令行支持:
  200. '     检测环境:IsCmdMode是否在CMD下运行
  201. '     模拟命令:Exist是否存在文件或文件夹、MD创建目录、Copy复制文件或文件夹、Del删除文件或文件夹、
  202. '               Attrib更改文件或文件夹属性、Ping检测网络联通、
  203. ' 对话框:
  204. '     提示消息:WarningInfo警告消息、TipInfo提示消息、ErrorInfo错误消息
  205. '     输入密码:GetPassword提示输入密码、
  206. ' 文件系统:
  207. '     复制、删除、更改属性:参考“命令行支持”。
  208. '     INI文件处理:
  209. '     注册表处理:RegRead读注册表、RegWrite写注册表
  210. '     日志处理:WriteLog写文本日志
  211. ' 字符串处理:
  212. '     提取:RegExpTest
  213. ' 程序:
  214. '     检测:IsRun是否运行、MeIsAlreadyRun本程序是否执行、、、、
  215. '     执行:Run前台等待执行、RunHide隐藏等待执行、RunNotWait前台不等待执行、RunHideNotWite后台不等待执行、
  216. '     加密运行:MeEncoder
  217. ' 系统:
  218. '     版本
  219. '     延时:Sleep
  220. '     发送按键:SendKeys
  221. ' 网络:
  222. '     检测:Ping、参考“命令行支持”。
  223. '     连接:文件共享、、、、、、、、、、
  224. ' 时间:Format_Time格式化时间、NowDateTime当前时间
  225. ' ====================================================================================================
  226. ' ====================================================================================================
  227. ' 小函数
  228. Sub Sleep( sTime )                          ' 延时 sTime 毫秒
  229.     WScript.Sleep sTime
  230. End Sub
  231. Sub SendKeys( strKey )                      ' 发送按键
  232.     CreateObject("WScript.Shell").SendKeys strKey
  233. End Sub
  234. ' KeyCode - 按键代码:
  235. ' Shift +       *Ctrl ^     *Alt %     *BACKSPACE {BACKSPACE}, {BS}, or {BKSP}      *BREAK {BREAK}
  236. ' CAPS LOCK {CAPSLOCK}      *DEL or DELETE {DELETE} or {DEL}     *DOWN ARROW {DOWN}     *END {END}
  237. ' ENTER {ENTER}or ~     *ESC {ESC}     *HELP {HELP}   *HOME {HOME}   *INS or INSERT {INSERT} or {INS}
  238. ' LEFT ARROW {LEFT}     *NUM LOCK {NUMLOCK}    *PAGE DOWN {PGDN}     *PAGE UP {PGUP}    *PRINT SCREEN {PRTSC}
  239. ' RIGHT ARROW {RIGHT}   *SCROLL LOCK {SCROLLLOCK}      *TAB {TAB}    *UP ARROW {UP}     *F1 {F1}   *F16 {F16}
  240. ' 实例:切换输入法(模拟同时按下:Shift、Ctrl键)"+(^)" ;重启电脑(模拟按下:Ctrl + Esc、u、r键): "^{ESC}ur" 。
  241. ' 同时按键:在按 e和 c的同时按 SHIFT 键: "+(ec)" ;在按 e时只按 c(而不按 SHIFT): "+ec" 。
  242. ' 重复按键:按 10 次 "x": "{x 10}"。按键和数字间有空格。
  243. ' 特殊字符:发送 “+”、“^” 特殊的控制按键:"{+}"、"{^}"
  244. ' 注意:只可以发送重复按一个键的按键。例如,可以发送 10次 "x",但不可发送 10次 "Ctrl+x"。  
  245. ' 注意:不能向应用程序发送 PRINT SCREEN键{PRTSC}。
  246. Function AppActivate( strWindowTitle )      ' 激活标题包含指定字符窗口,例如判断D盘是否被打开If AppActivate("(D:)") Then
  247.     AppActivate = CreateObject("WScript.Shell").AppActivate( strWindowTitle )
  248. End Function
  249. ' ====================================================================================================
  250. ' ShowMsg 消息弹窗
  251. Sub WarningInfo( strTitle, strMsg, sTime )
  252.     CreateObject("wscript.Shell").popup strMsg, sTime , strTitle, 48+4096    ' 提示信息
  253. End Sub
  254. Sub TipInfo( strTitle, strMsg, sTime )
  255.     CreateObject("wscript.Shell").popup strMsg, sTime , strTitle, 64+4096    ' 提示信息
  256. End Sub
  257. Sub ErrorInfo( strTitle, strMsg, sTime )
  258.     CreateObject("wscript.Shell").popup strMsg, sTime , strTitle, 16+4096    ' 提示信息
  259. End Sub
  260. ' ====================================================================================================
  261. ' RunApp 执行程序
  262. Sub Run( strCmd )
  263.     CreateObject("WScript.Shell").Run strCmd, 1, True       ' 正常运行 + 等待程序运行完成
  264. End Sub
  265. Sub RunNotWait( strCmd )
  266.     CreateObject("WScript.Shell").Run strCmd, 1, False      ' 正常运行 + 不等待程序运行完成
  267. End Sub
  268. Sub RunHide( strCmd )
  269.     CreateObject("WScript.Shell").Run strCmd, 0, True       ' 隐藏后台运行 + 等待程序运行完成
  270. End Sub
  271. Sub RunHideNotWait( strCmd )
  272.     CreateObject("WScript.Shell").Run strCmd, 0, False      ' 隐藏后台运行 + 不等待程序运行完成
  273. End Sub
  274. ' ====================================================================================================
  275. ' CMD 命令集
  276. ' ----------------------------------------------------------------------------------------------------
  277. ' ----------------------------------------------------------------------------------------------------
  278. ' 检测是否运行于CMD模式
  279. Function IsCmdMode()
  280.     IsCmdMode = False
  281.     If (LCase(Right(WScript.FullName,11)) = LCase("CScript.exe")) Then IsCmdMode = True
  282. End Function
  283. ' Exist 检测文件或文件夹是否存在
  284. Function Exist( strPath )
  285.     Exist = False
  286.     Set fso = CreateObject("Scripting.FileSystemObject")
  287.     If ((fso.FolderExists(strPath)) Or (fso.FileExists(strPath))) Then Exist = True
  288.     Set fso = Nothing
  289. End Function
  290. ' ----------------------------------------------------------------------------------------------------
  291. ' MD 创建文件夹路径
  292. Sub MD( ByVal strPath )
  293.     Dim arrPath, strTemp, valStart
  294.     arrPath = Split(strPath, "\")
  295.     If Left(strPath, 2) = "\\" Then    ' UNC Path
  296.         valStart = 3
  297.         strTemp = arrPath(0) & "\" & arrPath(1) & "\" & arrPath(2)
  298.     Else                              ' Local Path
  299.         valStart = 1
  300.         strTemp = arrPath(0)
  301.     End If
  302.     Set fso = CreateObject("Scripting.FileSystemObject")
  303.     For i = valStart To UBound(arrPath)
  304.         strTemp = strTemp & "\" & arrPath(i)
  305.         If Not fso.FolderExists( strTemp ) Then fso.CreateFolder( strTemp )
  306.     Next
  307.     Set fso = Nothing
  308. End Sub
  309. ' ----------------------------------------------------------------------------------------------------
  310. ' copy 复制文件或文件夹
  311. Sub Copy( ByVal strSource, ByVal strDestination )
  312.     On Error Resume Next ' Required 必选
  313.     Set fso = CreateObject("Scripting.FileSystemObject")
  314.     If (fso.FileExists(strSource)) Then               ' 如果来源是一个文件
  315.         If (fso.FolderExists(strDestination)) Then    ' 如果目的地是一个文件夹,加上路径后缀反斜线“\”
  316.             fso.CopyFile fso.GetFile(strSource).Path, fso.GetFolder(strDestination).Path & "\", True
  317.         Else                                          ' 如果目的地是一个文件,直接复制
  318.             fso.CopyFile fso.GetFile(strSource).Path, strDestination, True
  319.         End If
  320.     End If                                             ' 如果来源是一个文件夹,复制文件夹
  321.     If (fso.FolderExists(strSource)) Then fso.CopyFolder fso.GetFolder(strSource).Path, fso.GetFolder(strDestination).Path, True
  322.     Set fso = Nothing
  323. End Sub
  324. ' ----------------------------------------------------------------------------------------------------
  325. ' del 删除文件或文件夹
  326. Sub Del( strPath )
  327.     On Error Resume Next ' Required 必选
  328.     Set fso = CreateObject("Scripting.FileSystemObject")
  329.     If (fso.FileExists(strPath)) Then
  330.         fso.GetFile( strPath ).attributes = 0
  331.         fso.GetFile( strPath ).delete
  332.     End If
  333.     If (fso.FolderExists(strPath)) Then
  334.         fso.GetFolder( strPath ).attributes = 0
  335.         fso.GetFolder( strPath ).delete
  336.     End If
  337.     Set fso = Nothing
  338. End Sub
  339. ' ----------------------------------------------------------------------------------------------------
  340. ' attrib 改变文件属性
  341. Sub Attrib( strPath, strArgs )    'strArgs = [+R | -R] [+A | -A ] [+S | -S] [+H | -H]
  342.     Dim fso, valAttrib, arrAttrib()
  343.     Set fso = CreateObject("Scripting.FileSystemObject")
  344.     If (fso.FileExists(strPath)) Then valAttrib = fso.getFile( strPath ).attributes
  345.     If (fso.FolderExists(strPath)) Then valAttrib = fso.getFolder( strPath ).attributes
  346.     If valAttrib = "" Or strArgs = "" Then Exit Sub
  347.     binAttrib = DecToBin(valAttrib)   ' 十进制转二进制
  348.     For i = 0 To 16                   ' 二进制转16位二进制
  349.         ReDim Preserve arrAttrib(i) : arrAttrib(i) = 0
  350.         If i > 16-Len(binAttrib) Then arrAttrib(i) = Mid(binAttrib, i-(16-Len(binAttrib)), 1)
  351.     Next
  352.     If Instr(1, LCase(strArgs), "+r", 1) Then arrAttrib(16-0) = 1   'ReadOnly 1 只读文件。
  353.     If Instr(1, LCase(strArgs), "-r", 1) Then arrAttrib(16-0) = 0
  354.     If Instr(1, LCase(strArgs), "+h", 1) Then arrAttrib(16-1) = 1   'Hidden 2 隐藏文件。
  355.     If Instr(1, LCase(strArgs), "-h", 1) Then arrAttrib(16-1) = 0
  356.     If Instr(1, LCase(strArgs), "+s", 1) Then arrAttrib(16-2) = 1   'System 4 系统文件。
  357.     If Instr(1, LCase(strArgs), "-s", 1) Then arrAttrib(16-2) = 0
  358.     If Instr(1, LCase(strArgs), "+a", 1) Then arrAttrib(16-5) = 1   'Archive 32 上次备份后已更改的文件。
  359.     If Instr(1, LCase(strArgs), "-a", 1) Then arrAttrib(16-5) = 0
  360.     valAttrib = BinToDec(Join(arrAttrib,""))   ' 二进制转十进制
  361.     If (fso.FileExists(strPath)) Then fso.getFile( strPath ).attributes = valAttrib
  362.     If (fso.FolderExists(strPath)) Then fso.getFolder( strPath ).attributes = valAttrib
  363.     Set fso = Nothing
  364. End Sub
  365. Function DecToBin(ByVal number)    ' 十进制转二进制
  366.    Dim remainder
  367.    remainder = number
  368.    Do While remainder > 0
  369.       DecToBin = CStr(remainder Mod 2) & DecToBin
  370.       remainder = remainder \ 2
  371.    Loop
  372. End Function
  373. Function BinToDec(ByVal binStr)    ' 二进制转十进制
  374.    Dim i
  375.    For i = 1 To Len(binStr)
  376.       BinToDec = BinToDec + (CInt(Mid(binStr, i, 1)) * (2 ^ (Len(binStr) - i)))
  377.    Next
  378. End Function
  379. ' ----------------------------------------------------------------------------------------------------
  380. ' Ping 判断网络是否联通
  381. Function Ping(host)
  382.     On Error Resume Next
  383.     Ping = False :   If host = "" Then Exit Function
  384.     Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & host & "'")
  385.     For Each objStatus in objPing
  386.         If objStatus.ResponseTime >= 0 Then Ping = True :   Exit For
  387.     Next
  388.     Set objPing = nothing
  389. End Function
  390. ' ====================================================================================================
  391. ' 获取当前的日期时间,并格式化
  392. Function NowDateTime()
  393.     'MyWeek = "周" & Right(WeekdayName(Weekday(Date())), 1) & " "
  394.     MyWeek = ""
  395.     NowDateTime = MyWeek & Format_Time(Now(),2) & " " & Format_Time(Now(),3)
  396. End Function
  397. Function Format_Time(s_Time, n_Flag)
  398.     Dim y, m, d, h, mi, s
  399.     Format_Time = ""
  400.     If IsDate(s_Time) = False Then Exit Function
  401.     y = cstr(year(s_Time))
  402.     m = cstr(month(s_Time))
  403.         If len(m) = 1 Then m = "0" & m
  404.     d = cstr(day(s_Time))
  405.         If len(d) = 1 Then d = "0" & d
  406.     h = cstr(hour(s_Time))
  407.         If len(h) = 1 Then h = "0" & h
  408.     mi = cstr(minute(s_Time))
  409.         If len(mi) = 1 Then mi = "0" & mi
  410.     s = cstr(second(s_Time))
  411.         If len(s) = 1 Then s = "0" & s
  412.     Select Case n_Flag
  413.         Case 1
  414.             Format_Time = y  & m & d  & h  & mi  & s    ' yyyy-mm-dd hh:mm:ss
  415.         Case 2
  416.             Format_Time = y & "-" & m & "-" & d    ' yyyy-mm-dd
  417.         Case 3
  418.             Format_Time = h & ":" & mi & ":" & s   ' hh:mm:ss
  419.         Case 4
  420.             Format_Time = y & "年" & m & "月" & d & "日"    ' yyyy年mm月dd日
  421.         Case 5
  422.             Format_Time = y & m & d    ' yyyymmdd
  423.     End Select
  424. End Function
  425. ' ====================================================================================================
  426. ' 检查字符串是否符合正则表达式
  427. 'Msgbox Join(RegExpTest( "[A-z]+-[A-z]+", "a-v d-f b-c" ,"Value"), VbCrLf)
  428. 'Msgbox RegExpTest( "[A-z]+-[A-z]+", "a-v d-f b-c" ,"Count")
  429. 'Msgbox RegExpTest( "[A-z]+-[A-z]+", "a-v d-f b-c" ,"")
  430. Function RegExpTest(patrn, strng, mode)
  431.     Dim regEx, Match, Matches      ' 建立变量。
  432.     Set regEx = New RegExp         ' 建立正则表达式。
  433.         regEx.Pattern = patrn      ' 设置模式。
  434.         regEx.IgnoreCase = True    ' 设置是否区分字符大小写。
  435.         regEx.Global = True        ' 设置全局可用性。
  436.     Dim RetStr, arrMatchs(), i  :  i = -1
  437.     Set Matches = regEx.Execute(strng)     ' 执行搜索。
  438.     For Each Match in Matches              ' 遍历匹配集合。
  439.         i = i + 1
  440.         ReDim Preserve arrMatchs(i)        ' 动态数组:数组随循环而变化
  441.         arrMatchs(i) = Match.Value
  442.         RetStr = RetStr & "Match found at position " & Match.FirstIndex & ". Match Value is '" & Match.Value & "'." & vbCRLF
  443.     Next
  444.     If LCase(mode) = LCase("Value") Then RegExpTest = arrMatchs       ' 以数组返回所有符合表达式的所有数据
  445.     If LCase(mode) = LCase("Count") Then RegExpTest = Matches.Count   ' 以整数返回符合表达式的所有数据总数
  446.     If IsEmpty(RegExpTest) Then RegExpTest = RetStr                   ' 返回所有匹配结果
  447. End Function
  448. '===========================================================================================
  449. '读写注册表
  450. '读注册表
  451. Function RegRead( strKey )
  452.     On Error Resume Next
  453.     Set wso = CreateObject("WScript.Shell")
  454.     RegRead = wso.RegRead( strKey )    'strKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\DocTip"
  455.     If IsArray( RegRead ) Then RegRead = Join(RegRead, VbCrLf)
  456.     Set wso = Nothing
  457. End Function
  458. '写注册表
  459. Function RegWrite( strKey, strKeyVal, strKeyType )
  460.     On Error Resume Next
  461.     Dim fso, strTmp
  462.     RegWrite = Flase
  463.     Set wso = CreateObject("WScript.Shell")
  464.     wso.RegWrite strKey, strKeyVal, strKeyType
  465.     strTmp = wso.RegRead( strKey )
  466.     If strTmp <> "" Then RegWrite = True
  467.     Set wso = Nothing
  468. End Function
  469. ' ====================================================================================================
  470. ' 写文本日志
  471. Sub WriteLog(str, file)
  472.     If (file = "") Or (str = "") Then Exit Sub
  473.     str = NowDateTime & "   " & str & VbCrLf
  474.     Dim fso, wtxt
  475.     Const ForAppending = 8         'ForReading = 1 (只读不写), ForWriting = 2 (只写不读), ForAppending = 8 (在文件末尾写)
  476.     Const Create = True            'Boolean 值,filename 不存在时是否创建新文件。允许创建为 True,否则为 False。默认值为 False。
  477.     Const TristateTrue = -1        'TristateUseDefault = -2 (SystemDefault), TristateTrue = -1 (Unicode), TristateFalse = 0 (ASCII)
  478.    
  479.     On Error Resume  Next
  480.     Set fso = CreateObject("Scripting.filesystemobject")
  481.     set wtxt = fso.OpenTextFile(file, ForAppending, Create, TristateTrue)
  482.     wtxt.Write str
  483.     wtxt.Close()
  484.     set fso = Nothing
  485.     set wtxt = Nothing
  486. End Sub
  487. ' ====================================================================================================
  488. ' 程序控制
  489. ' 检测是否运行
  490. Function IsRun(byVal AppName, byVal AppPath)   ' Eg: Call IsRun("mshta.exe", "c:\test.hta")
  491.     IsRun = 0 : i = 0
  492.     For Each ps in GetObject("winmgmts:\\.\root\cimv2:win32_process").instances_
  493.         IF LCase(ps.name) = LCase(AppName) Then
  494.             If AppPath = "" Then IsRun = 1 : Exit Function
  495.             IF Instr( LCase(ps.CommandLine) , LCase(AppPath) ) Then i = i + 1
  496.         End IF
  497.     Next
  498.     IsRun = i
  499. End Function
  500. ' ----------------------------------------------------------------------------------------------------
  501. ' 检测自身是否重复运行
  502. Function MeIsAlreadyRun()
  503.     MeIsAlreadyRun = False
  504.     If ((IsRun("WScript.exe",WScript.ScriptFullName)>1) Or (IsRun("CScript.exe",WScript.ScriptFullName)>1)) Then MeIsAlreadyRun = True
  505. End Function
  506. ' ----------------------------------------------------------------------------------------------------
  507. ' 关闭进程
  508. Sub Close_Process(ProcessName)
  509.     'On Error Resume Next
  510.     For each ps in getobject("winmgmts:\\.\root\cimv2:win32_process").instances_    '循环进程
  511.         If Ucase(ps.name)=Ucase(ProcessName) Then
  512.             ps.terminate
  513.         End if
  514.     Next
  515. End Sub
  516. ' ====================================================================================================
  517. ' 系统
  518. ' 检查操作系统版本
  519. Sub CheckOS()
  520.     If LCase(OSVer()) <> "xp" Then
  521.         Msgbox "不支持该操作系统!    ", 48+4096, "警告"
  522.         WScript.Quit    ' 退出程序
  523.     End If
  524. End Sub
  525. ' ----------------------------------------------------------------------------------------------------
  526. ' 取得操作系统版本
  527. Function OSVer()
  528.     Dim objWMI, objItem, colItems
  529.     Dim strComputer, VerOS, VerBig, Ver9x, Version9x, OS, OSystem
  530.     strComputer = "."
  531.     Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  532.     Set colItems = objWMI.ExecQuery("Select * from Win32_OperatingSystem",,48)
  533.     For Each objItem in colItems
  534.         VerBig = Left(objItem.Version,3)
  535.     Next
  536.     Select Case VerBig
  537.         Case "6.1" OSystem = "Win7"
  538.         Case "6.0" OSystem = "Vista"
  539.         Case "5.2" OSystem = "Windows 2003"
  540.         Case "5.1" OSystem = "XP"
  541.         Case "5.0" OSystem = "W2K"
  542.         Case "4.0" OSystem = "NT4.0"
  543.         Case Else OSystem = "Unknown"
  544.                   If CInt(Join(Split(VerBig,"."),"")) < 40 Then OSystem = "Win9x"
  545.     End Select
  546.     OSVer = OSystem
  547. End Function
  548. ' ----------------------------------------------------------------------------------------------------
  549. ' 取得操作系统预言
  550. Function language()
  551.     Dim strComputer, objWMIService, colItems, strLanguageCode, strLanguage
  552.     strComputer = "."
  553.     Set objWMIService = GetObject("winmgmts://" &strComputer &"/root/CIMV2")
  554.     Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem")
  555.     For Each objItem In colItems
  556.         strLanguageCode = objItem.OSLanguage
  557.     Next
  558.     Select Case strLanguageCode
  559.         Case "1033" strLanguage = "en"
  560.         Case "2052" strLanguage = "chs"
  561.         Case Else  strLanguage = "en"
  562.     End Select
  563.     language = strLanguage
  564. End Function
  565. ' ====================================================================================================
  566. ' 加密自身
  567. Sub MeEncoder()
  568.     Dim MeAppPath, MeAppName, MeAppFx, MeAppEncodeFile, data
  569.     MeAppPath = left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName,"\"))
  570.     MeAppName = Left( WScript.ScriptName, InStrRev(WScript.ScriptName,".") - 1 )
  571.     MeAppFx = Right(WScript.ScriptName, Len(WScript.ScriptName) - InStrRev(WScript.ScriptName,".") + 1 )
  572.     MeAppEncodeFile = MeAppPath & MeAppName & ".s.vbe"
  573.     If Not ( LCase(MeAppFx) = LCase(".vbs") ) Then Exit Sub
  574.     Set fso = CreateObject("Scripting.FileSystemObject")
  575.     data = fso.OpenTextFile(WScript.ScriptFullName, 1, False, -1).ReadAll
  576.     data = CreateObject("Scripting.Encoder").EncodeScriptFile(".vbs", data, 0, "VBScript")
  577.     fso.OpenTextFile(MeAppEncodeFile, 2, True, -1).Write data
  578.     MsgBox "编码完毕,文件生成到:" & vbCrLf & vbCrLf & MeAppEncodeFile, 64+4096, WScript.ScriptName
  579.     Set fso = Nothing
  580.     WScript.Quit
  581. End Sub
  582. ' ====================================================================================================
  583. ' 初始化全局变量
  584. Sub GetGloVar()
  585.     WhoAmI = CreateObject( "WScript.Network" ).ComputerName & "\" & CreateObject( "WScript.Network" ).UserName  ' 使用者信息
  586.     TmpDir = CreateObject("Scripting.FileSystemObject").getspecialfolder(2) & "\"                               ' 临时文件夹路径
  587.     WinDir = CreateObject("wscript.Shell").ExpandenVironmentStrings("%windir%") & "\"                           ' 本机 %Windir% 文件夹路径
  588.     AppDataDir = CreateObject("WScript.Shell").SpecialFolders("AppData") & "\"                                  ' 本机 %AppData% 文件夹路径
  589.     StartupDir = CreateObject("WScript.Shell").SpecialFolders("Startup") & "\"                                  ' 本机启动文件夹路径
  590.     MeDir = Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName,"\"))                                  ' 脚本所在文件夹路径
  591.     ' 脚本位于共享的目录时,取得共享的电脑名(UNCHost),进行位置验证(If UNCHost <> "SerNTF02" Then WScript.Quit) ' 防止拷贝到本地运行
  592.     UNCHost = LCase(Mid(WScript.ScriptFullName,InStr(WScript.ScriptFullName,"\\")+2,InStr(3,WScript.ScriptFullName,"\",1)-3))
  593. End Sub
复制代码

作者: hlzj88    时间: 2014-4-24 20:57

本帖最后由 hlzj88 于 2014-4-24 20:58 编辑

使用vbs添加网络打印机  
根据实际环境更改打印服务器和打印机名称,此代码会在本地计算机上添加一个网络打印机,并设置为默认打印机,代码如下:

Set WshNetwork = CreateObject("WScript.Network")
WshNetwork.AddWindowsPrinterConnection "\\192.168.0.154\HP"
WshNetwork.SetDefaultPrinter "\\192.168.0.154\HP"

另存为print.vbs,当局域网内部哪一台电脑需要安装这个打印机只需要直接运行此脚本就可以安装好.

以上内容来自网络




欢迎光临 批处理之家 (http://bathome.net./) Powered by Discuz! 7.2