[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[问题求助] VBS如何在域内安装共享打印机?如能帮忙解决,汇RMB都可以哈!

各位大神,小弟有件急事,需要编写一个VBS脚本完成的。
  1. On Error Resume Next
  2. Set WshNetwork = WScript.CreateObject("WScript.Network")
  3. WshNetwork.AddwindowsPrinterConnection "\\打印服务器地址\共享打印机A"
  4. WshNetwork.AddwindowsPrinterConnection "\\打印服务器地址\共享打印机B"
  5. WshNetwork.SetDefaultPrinter "\\打印服务器地址\共享打印机A"
复制代码
看以上的编写就是需要在域内安装共享打印机,并将其中一个设定为默认设备。

现在问题来了噢???
Client设备上已安装有打印机A\B或A\C或A\B\C(有的安装了2个驱动,有的是3个、有的是4个),如何判断Client安装的打印机并进行覆盖呢?默认状态下Client只需推送安装2个驱动,若Client已安装了4个驱动,则只能覆盖其中2个,另外2个未覆盖的将不能使用造成不便。加入检索功能后,Client已安装4个驱动则自动覆盖4个,如此类推。
类似的脚本应该如何编写!!!! :$ :$

发一个本人正在用的,需要管理员权限。安装驱动时会出现安装界面。

查看打印机可使用 ShowPrint( "." ) 函数。

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

TOP

回复 2# yu2n

大神,好复杂噢!!!我要慢慢去消化!!!OK汇款哈。

TOP

回复 2# yu2n


    请问能再简单点说明或直接编写一个能直接运行的脚本嚒,本人真的一点都不懂咧 :'(

TOP

回复 4# hitpop

这位兄台,这个不是两三行代码的事,系统环境、需求还不明朗。
暂时没有时间,有空再看看吧。
『千江有水千江月』千江有水,月映千江;万里无云,万里青天。    http://yu2n.qiniudn.com/

TOP

返回列表