Что нового

[Автоматизация] изменение bat для установки драйвера

daradan

Новичок
Сообщения
13
Репутация
0
Здравствуйте!
Имеется bat-файл для установки принтера и сканера подключенный по TCP\IP.
Код:
hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "10.9.40.43" -n 1
и
Код:
cscript prnport.vbs -a -r IP_10.9.40.43 -h 10.9.40.43 -o raw -n 9100
rundll32 printui.dll,PrintUIEntry /if /b "1522_40.43" /f hppcp608.inf /r "IP_10.9.40.43" /m "HP LaserJet M1522 MFP Series PCL 6"
Как можно сделать в интерфейсе менять значении IP? Просто приходится каждый раз изменять IP вручную с помощью блокнота. :-[
Заранее спасибо!
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
Код:
Run('hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "[b]'&@IPAddress1&'[/b]" -n 1')
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Код:
#include <GUIConstantsEx.au3>

_Main()

Func _Main()
	Local $inputbutton, $okbutton, $cancelbutton
	#forceref $separator1

	GUICreate("Установка сканера HP LJ M1522", 300, 100)

	$inputbutton = GUICtrlCreateInput("Введите IP", 50, 20, 100, 20)
	
	$okbutton = GUICtrlCreateButton("OK", 50, 50, 70, 20)

	$cancelbutton = GUICtrlCreateButton("Отмена", 180, 50, 70, 20)

	GUISetState()

	While 1
		$msg = GUIGetMsg()


		Select
			Case $msg = $GUI_EVENT_CLOSE Or $msg = $cancelbutton
				ExitLoop

			Case $inputbutton = $okbutton
				Run('hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'$inputbutton'" -n 1')

			
		EndSelect
	WEnd

	GUIDelete()

	Exit
EndFunc   ;==>_Main

Примерно сделал :-[ . Подскажите как сделать, чтобы при нажатии на ОК, изменилось значение $inputbutton на которое введено в поле $inputbutton
OffTopic:
Сильно не пинайте, только начал изучать :'(
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
Код:
GUICreate("Установка сканера HP LJ M1522", 300, 100)
$inputbutton = GUICtrlCreateInput("Введите IP", 50, 20, 100, 20)
$okbutton = GUICtrlCreateButton("OK", 50, 50, 70, 20)
$cancelbutton = GUICtrlCreateButton("Отмена", 180, 50, 70, 20)
GUISetState()
While 1
$msg = GUIGetMsg()
Select
Case $msg = -3 Or $msg = $cancelbutton
ExitLoop
Case $okbutton
If StringLen(GUICtrlRead($inputbutton))=0 Then Exit 1
Run('hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&GUICtrlRead($inputbutton)&'" -n 1')
EndSelect
WEnd
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Извиняюсь еще раз...

Как можно запустить RUN, если bat-файл имеет такое:
Код:
cscript prnport.vbs -a -r IP_'&GUICtrlRead($inputbutton)&' -h '&GUICtrlRead($inputbutton)&' -o raw -n 9100
rundll32 printui.dll,PrintUIEntry /if /b "1522_'&GUICtrlRead($inputbutton)&'" /f hppcp608.inf /r "'&GUICtrlRead($inputbutton)&'" /m "HP LaserJet M1522 MFP Series PCL 6"
После конвертировании в exe и при запуске, запускаются несколько копии cmd и комп виснет. В диспетчере задач появляется несколько копии rundll32
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
Покажи что находиться в prnport.vbs.
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Покажи что находиться в prnport.vbs.
Код:
'----------------------------------------------------------------------
'
' Copyright (c) Microsoft Corporation. All rights reserved.
'
' Abstract:
' prnport.vbs - Port script for WMI on Whistler
'     used to add, delete and list ports
'     also for getting and setting the port configuration
'
' Usage:
' prnport [-adlgt?] [-r port] [-s server] [-u user name] [-w password] 
'                   [-o raw|lpr] [-h host address] [-q queue] [-n number]
'                   [-me | -md ] [-i SNMP index] [-y community] [-2e | -2d]"
'
' Examples
' prnport -a -s server -r IP_1.2.3.4 -e 1.2.3.4 -o raw -n 9100
' prnport -d -s server -r c:\temp\foo.prn
' prnport -l -s server
' prnport -g -s server -r IP_1.2.3.4
' prnport -t -s server -r IP_1.2.3.4 -me -y public -i 1 -n 9100
'
'----------------------------------------------------------------------

option explicit

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

gDebugFlag = false

'
' Operation action values.
'
const kActionAdd          = 0
const kActionDelete       = 1
const kActionList         = 2
const kActionUnknown      = 3
const kActionGet          = 4
const kActionSet          = 5

const kErrorSuccess       = 0
const KErrorFailure       = 1

const kFlagCreateOrUpdate = 0

const kNameSpace          = "root\cimv2"


'
' Constants for the parameter dictionary
'
const kServerName      = 1
const kPortName        = 2
const kDoubleSpool     = 3
const kPortNumber      = 4
const kPortType        = 5
const kHostAddress     = 6
const kSNMPDeviceIndex = 7
const kCommunityName   = 8
const kSNMP            = 9
const kQueueName       = 10  
const kUserName        = 11
const kPassword        = 12

'
' 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                 = "Отладка:"

'
' General usage messages
'                                 
const L_Help_Help_General01_Text   = "Использование: prnport [-adlgt?] [-r порт][-s сервер][-u имя пользователя][-w пароль]"
const L_Help_Help_General02_Text   = "               [-o raw|lpr][-h адрес узла][-q очередь][-n номер]"
const L_Help_Help_General03_Text   = "               [-me | -md ][-i SNMP индекс][-y community][-2e | -2d]"
const L_Help_Help_General04_Text   = "Аргументы:"
const L_Help_Help_General05_Text   = "-a     - добавление порта"
const L_Help_Help_General06_Text   = "-d     - удаление указанного порта"
const L_Help_Help_General07_Text   = "-g     - получить настройку TCP -порта"
const L_Help_Help_General08_Text   = "-h     - IP-адрес устройства"
const L_Help_Help_General09_Text   = "-i     - SNMP-инднекс, если SNMP запрещен"
const L_Help_Help_General10_Text   = "-l     - перечисление всех TCP-портов"
const L_Help_Help_General11_Text   = "-m     - SNMP-тип, [e] разрешен, [d] запрещен"
const L_Help_Help_General12_Text   = "-n     - номер порта, применяется для TCP RAW-портов"
const L_Help_Help_General13_Text   = "-o     - тип потра. RAW или LPR"
const L_Help_Help_General14_Text   = "-q     - имя очереди, применяется для TCP LPR -портов"
const L_Help_Help_General15_Text   = "-r     - имя порта"
const L_Help_Help_General16_Text   = "-s     - имя сервера"
const L_Help_Help_General17_Text   = "-t     - настройка  для TCP-портов"
const L_Help_Help_General18_Text   = "-u     - имя пользователя"
const L_Help_Help_General19_Text   = "-w     - пароль"
const L_Help_Help_General20_Text   = "-y     - имя community, если разрешен SNMP"
const L_Help_Help_General21_Text   = "-2     - двойная очередь, применима для TCP LPR-портов. [e] разрешена. [d] не разрешен"
const L_Help_Help_General22_Text   = "-?     - отобразить использование команды"
const L_Help_Help_General23_Text   = "Примеры:"
const L_Help_Help_General24_Text   = "prnport -l -s сервер"
const L_Help_Help_General25_Text   = "prnport -d -s сервер -r IP_1.2.3.4"
const L_Help_Help_General26_Text   = "prnport -a -s сервер -r IP_1.2.3.4 -h 1.2.3.4 -o RAW -n 9100"
const L_Help_Help_General27_Text   = "prnport -t -s сервер -r IP_1.2.3.4 -мой -y общественный -i 1 -n 9100"
const L_Help_Help_General28_Text   = "prnport -g -s сервер -r IP_1.2.3.4"
const L_Help_Help_General29_Text   = "prnport -a -r IP_1.2.3.4 -h 1.2.3.4"
const L_Help_Help_General30_Text   = "Примечание:"
const L_Help_Help_General31_Text   = "Последний пример будет стараться получить данные о настройке устройства по указанному IP-адресу." 
const L_Help_Help_General32_Text   = "Если устройство обнаружено, то TCP-порт добавлен к устройству с предпочитаемыми параметрами."

'
' Messages to be displayed if the scripting host is not cscript
'                            
const L_Help_Help_Host01_Text      = "Запустите данный скрипт с использованием CScript."  
const L_Help_Help_Host02_Text      = "Можно достичь"
const L_Help_Help_Host03_Text      = "1. Использование ""CScript script.vbs arguments"" или" 
const L_Help_Help_Host04_Text      = "2. Замена указанного узла Windows на  CScript"
const L_Help_Help_Host05_Text      = "   использование ""CScript //H:CScript //S"" и запуск скрипта"
const L_Help_Help_Host06_Text      = "   ""script.vbs arguments""."

'
' General error messages
'                                                 
const L_Text_Error_General01_Text  = "Не удалось определить указанный узел."                
const L_Text_Error_General02_Text  = "Не удается обработать командную строку." 
const L_Text_Error_General03_Text  = "код  ошибки Win32"

'
' Miscellaneous messages
'
const L_Text_Msg_General01_Text    = "Добавленный порт"
const L_Text_Msg_General02_Text    = "Не удается удалить порт"
const L_Text_Msg_General03_Text    = "Не удается получить порт"
const L_Text_Msg_General04_Text    = "Созданный или обновленный порт"
const L_Text_Msg_General05_Text    = "Не удается создать или обновить порт"
const L_Text_Msg_General06_Text    = "Не удается пронумеровать порт"
const L_Text_Msg_General07_Text    = "Число пронумерованных портов"
const L_Text_Msg_General08_Text    = "Удалить порт"
const L_Text_Msg_General09_Text    = "Не удается получить объект SWbemLocator"
const L_Text_Msg_General10_Text    = "Не удалось подключиться к WMI-службе"


'
' Port properties
'
const L_Text_Msg_Port01_Text       = "Имя сервера"
const L_Text_Msg_Port02_Text       = "Имя порта"
const L_Text_Msg_Port03_Text       = "Адрес узла"
const L_Text_Msg_Port04_Text       = "Протокол RAW"
const L_Text_Msg_Port05_Text       = "Протокол LPR"
const L_Text_Msg_Port06_Text       = "Порт"
const L_Text_Msg_Port07_Text       = "Очередь"
const L_Text_Msg_Port08_Text       = "Разрешен подсчет байт"
const L_Text_Msg_Port09_Text       = "Не разрешен подсчет байт"
const L_Text_Msg_Port10_Text       = "SNMP разрешен"
const L_Text_Msg_Port11_Text       = "SNMP запрещен"
const L_Text_Msg_Port12_Text       = "Сообщество"
const L_Text_Msg_Port13_Text       = "Индекс устройства"

'
' Debug messages
'
const L_Text_Dbg_Msg01_Text        = "Выполняется DelPort"
const L_Text_Dbg_Msg02_Text        = "Выполняется CreateOrSetPort"
const L_Text_Dbg_Msg03_Text        = "Выполняется ListPorts"
const L_Text_Dbg_Msg04_Text        = "Выполняется GetPort"
const L_Text_Dbg_Msg05_Text        = "В действии ParseCommandLine"

main

'
' Main execution starts here
'
sub main

    on error resume next

    dim iAction
    dim iRetval
    dim oParamDict

    '
    ' 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
    
    set oParamDict = CreateObject("Scripting.Dictionary")

    iRetval = ParseCommandLine(iAction, oParamDict)

    if iRetval = 0 then

        select case iAction

            case kActionAdd
                iRetval = CreateOrSetPort(oParamDict)

            case kActionDelete
                iRetval = DelPort(oParamDict)

            case kActionList
                iRetval = ListPorts(oParamDict)

            case kActionGet
                iRetVal = GetPort(oParamDict)

            case kActionSet
                iRetVal = CreateOrSetPort(oParamDict)

            case else
                Usage(true)
                exit sub

        end select

    end if

end sub

'
' Delete a port
'
function DelPort(oParamDict)

    on error resume next

    DebugPrint kDebugTrace, L_Text_Dbg_Msg01_Text
    DebugPrint kDebugTrace, L_Text_Msg_Port01_Text & L_Space_Text & oParamDict(kServerName)
    DebugPrint kDebugTrace, L_Text_Msg_Port02_Text & L_Space_Text & oParamDict(kPortName)
    
    dim oService
    dim oPort
    dim iResult
    dim strServer
    dim strPort
    dim strUser
    dim strPassword
    
    iResult = kErrorFailure
    
    strServer   = oParamDict(kServerName)
    strPort     = oParamDict(kPortName)
    strUser     = oParamDict(kUserName)
    strPassword = oParamDict(kPassword)
    
    if WmiConnect(strServer, kNameSpace, strUser, strPassword, oService) then

        set oPort = oService.Get("Win32_TCPIPPrinterPort='" & strPort & "'")

    else

        DelPort = kErrorFailure
        
        exit function        
    
    end if
    
    '
    ' Check if Get succeeded
    '
    if Err.Number = kErrorSuccess then 
    
        '
        ' Try deleting the instance
        '
        oPort.Delete_
        
        if Err.Number = kErrorSuccess then
        
            wscript.echo L_Text_Msg_General08_Text & L_Space_Text & strPort
        
        else
        
            wscript.echo L_Text_Msg_General02_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                         & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description
        
            '
            ' Try getting extended error information
            '
            call LastError()
        
        end if
        
    else
    
        wscript.echo L_Text_Msg_General02_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                     & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description
        
        '
        ' Try getting extended error information
        '
        call LastError()
    
    end if
    
    DelPort = iResult

end function

'
' Add or update a port
'
function CreateOrSetPort(oParamDict)

    on error resume next

    dim oPort
    dim oService
    dim iResult
    dim PortType
    dim strServer
    dim strPort
    dim strUser
    dim strPassword
    
    DebugPrint kDebugTrace, L_Text_Dbg_Msg02_Text
    DebugPrint kDebugTrace, L_Text_Msg_Port01_Text & L_Space_Text & oParamDict.Item(kServerName)
    DebugPrint kDebugTrace, L_Text_Msg_Port02_Text & L_Space_Text & oParamDict.Item(kPortName)  
    DebugPrint kDebugTrace, L_Text_Msg_Port06_Text & L_Space_Text & oParamDict.Item(kPortNumber)
    DebugPrint kDebugTrace, L_Text_Msg_Port07_Text & L_Space_Text & oParamDict.Item(kQueueName)
    DebugPrint kDebugTrace, L_Text_Msg_Port13_Text & L_Space_Text & oParamDict.Item(kSNMPDeviceIndex)
    DebugPrint kDebugTrace, L_Text_Msg_Port12_Text & L_Space_Text & oParamDict.Item(kCommunityName)
    DebugPrint kDebugTrace, L_Text_Msg_Port03_Text & L_Space_Text & oParamDict.Item(kHostAddress)
 
    strServer   = oParamDict(kServerName)
    strPort     = oParamDict(kPortName)
    strUser     = oParamDict(kUserName)
    strPassword = oParamDict(kPassword)

    '
    ' If the port exists, then get the settings. Later PutInstance will do an update
    '
    if WmiConnect(strServer, kNameSpace, strUser, strPassword, oService) then

        set oPort = oService.Get("Win32_TCPIPPrinterPort.Name='" & strPort & "'")
        
        '
        ' If get was unsuccessful then spwan a new port instance. Later PutInstance will do a create 
        '    
        if Err.Number <> kErrorSuccess then 

            '
            ' Clear the previous error
            ' 
            Err.Clear
    
            set oPort = oService.Get("Win32_TCPIPPrinterPort").SpawnInstance_

        end if 

    else

        CreateOrSetPort = kErrorFailure
        
        exit function        
    
    end if

    if Err.Number <> kErrorSuccess then
    
        wscript.echo L_Text_Msg_General03_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                     & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description
        
        CreateOrSetPort = kErrorFailure             
                     
        exit function
    
    end if

    oPort.Name   = oParamDict.Item(kPortName)
    PortType     = oParamDict.Item(kPortType)

    '
    ' Update the port object with the settings corresponding
    ' to the port type of the port to be added
    '
    select case lcase(PortType)

            case "raw"
                 oPort.Protocol      = 1
                 
            case "lpr"
                 oPort.Protocol      = 2
                 
            case else
            
                 '
                 ' PutInstance will attempt to get the configuration of 
                 ' the device based on its IP address. Those settings
                 ' will be used to add a new port
                 '
    end select
    
    oPort.HostAddress   = oParamDict.Item(kHostAddress)
    oPort.PortNumber    = oParamDict.Item(kPortNumber)
    oPort.SNMPEnabled   = oParamDict.Item(kSNMP)
    oPort.SNMPDevIndex  = oParamDict.Item(kSNMPDeviceIndex)
    oPort.SNMPCommunity = oParamDict.Item(kCommunityName)
    oPort.Queue         = oParamDict.Item(kQueueName)
    oPort.ByteCount     = oParamDict.Item(kDoubleSpool)

    '
    ' Try creating or updating the port
    '
    oPort.Put_(kFlagCreateOrUpdate)

    if Err.Number = kErrorSuccess then

        wscript.echo L_Text_Msg_General04_Text & L_Space_Text & oPort.Name

        iResult = kErrorSuccess

    else

        wscript.echo L_Text_Msg_General05_Text & L_Space_Text & oPort.Name & L_Space_Text _
                     & L_Error_Text & L_Space_Text & L_Hex_Text & hex(Err.Number) _ 
                     & L_Space_Text & Err.Description

        '
        ' Try getting extended error information
        '
        call LastError()

        iResult = kErrorFailure

    end if

    CreateOrSetPort = iResult

end function

'
' List ports on a machine.
'
function ListPorts(oParamDict)

    on error resume next

    DebugPrint kDebugTrace, L_Text_Dbg_Msg03_Text
    
    dim Ports
    dim oPort
    dim oService
    dim iRetval
    dim iTotal
    dim strServer
    dim strUser 
    dim strPassword
    
    iResult = kErrorFailure
    
    strServer   = oParamDict(kServerName)
    strUser     = oParamDict(kUserName)
    strPassword = oParamDict(kPassword)

    if WmiConnect(strServer, kNameSpace, strUser, strPassword, oService) then

        set Ports = oService.InstancesOf("Win32_TCPIPPrinterPort")

    else

        ListPorts = kErrorFailure
        
        exit function        
    
    end if
    
    if Err.Number <> kErrorSuccess then         
    
        wscript.echo L_Text_Msg_General06_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                     & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description

        ListPrinters = kErrorFailure
            
        exit function
        
    end if    
    
    iTotal = 0          
                  
    for each oPort in Ports

        iTotal = iTotal + 1
            
        wscript.echo L_Empty_Text
        wscript.echo L_Text_Msg_Port01_Text & L_Space_Text & strServer
        wscript.echo L_Text_Msg_Port02_Text & L_Space_Text & oPort.Name
        wscript.echo L_Text_Msg_Port03_Text & L_Space_Text & oPort.HostAddress         

        if oPort.Protocol = 1 then
            
            wscript.echo L_Text_Msg_Port04_Text
            wscript.echo L_Text_Msg_Port06_Text & L_Space_Text & oPort.PortNumber 
                
        else    
            
            wscript.echo L_Text_Msg_Port05_Text
            wscript.echo L_Text_Msg_Port07_Text & L_Space_Text & oPort.Queue
                
            if oPort.ByteCount then
                
                wscript.echo L_Text_Msg_Port08_Text 
                
            else
                
                wscript.echo L_Text_Msg_Port08_Text
                
            end if
                
        end if    
            
        if oPort.SNMPEnabled then
                
            wscript.echo L_Text_Msg_Port10_Text 
            wscript.echo L_Text_Msg_Port12_Text & L_Space_Text & oPort.SNMPCommunity
            wscript.echo L_Text_Msg_Port13_Text & L_Space_Text & oPort.SNMPDevIndex
                
        else
                
            wscript.echo L_Text_Msg_Port11_Text   
                
        end if
            
        Err.Clear
                                        
    next

    wscript.echo L_Empty_Text
    wscript.echo L_Text_Msg_General07_Text & L_Space_Text & iTotal 
    
    ListPorts = kErrorSuccess

end function

'
' Gets the configuration of a port
'
function GetPort(oParamDict)

    on error resume next

    DebugPrint kDebugTrace, L_Text_Dbg_Msg04_Text
    DebugPrint kDebugTrace, L_Text_Msg_Port01_Text & L_Space_Text & oParamDict(kServerName)
    DebugPrint kDebugTrace, L_Text_Msg_Port02_Text & L_Space_Text & oParamDict(kPortName)
    
    dim oService
    dim oPort
    dim iResult
    dim strServer
    dim strPort
    dim strUser 
    dim strPassword
    
    iResult = kErrorFailure
    
    strServer   = oParamDict(kServerName)
    strPort     = oParamDict(kPortName)
    strUser     = oParamDict(kUserName)
    strPassword = oParamDict(kPassword)

    if WmiConnect(strServer, kNameSpace, strUser, strPassword, oService) then

        set oPort = oService.Get("Win32_TCPIPPrinterPort.Name='" & strPort & "'")

    else

        GetPort = kErrorFailure
        
        exit function        
    
    end if

    if Err.Number = kErrorSuccess then 
            
        wscript.echo L_Empty_Text
        wscript.echo L_Text_Msg_Port01_Text & L_Space_Text & strServer
        wscript.echo L_Text_Msg_Port02_Text & L_Space_Text & oPort.Name
        wscript.echo L_Text_Msg_Port03_Text & L_Space_Text & oPort.HostAddress
            
        if oPort.Protocol = 1 then
            
            wscript.echo L_Text_Msg_Port04_Text
            wscript.echo L_Text_Msg_Port06_Text & L_Space_Text & oPort.PortNumber 
                
        else    
            
            wscript.echo L_Text_Msg_Port05_Text 
            wscript.echo L_Text_Msg_Port07_Text & L_Space_Text & oPort.Queue
                
            if oPort.ByteCount then
                
                wscript.echo L_Text_Msg_Port08_Text 
                
            else
                
                wscript.echo L_Text_Msg_Port09_Text   
                
            end if
                
        end if    
            
        if oPort.SNMPEnabled then
                
            wscript.echo L_Text_Msg_Port10_Text 
            wscript.echo L_Text_Msg_Port12_Text & L_Space_Text & oPort.SNMPCommunity
            wscript.echo L_Text_Msg_Port13_Text & L_Space_Text & oPort.SNMPDevIndex
                
        else
                
            wscript.echo L_Text_Msg_Port11_Text   
                
        end if
        
        iResult = kErrorSuccess
            
    else    
        
        wscript.echo L_Text_Msg_General03_Text & L_Space_Text & L_Error_Text & L_Space_Text _
                     & L_Hex_Text & hex(Err.Number) & L_Space_Text & Err.Description
        
        '
        ' Try getting extended error information
        '
        call LastError()
        
    end if

    GetPort = iResult

end function

'
' Debug display helper function
'
sub DebugPrint(uFlags, strString)

    if gDebugFlag = true then

        if uFlags = kDebugTrace then

            wscript.echo L_Debug_Text & L_Space_Text & strString

        end if

        if uFlags = kDebugError then

            if Err <> 0 then

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

            end if

        end if

    end if

end sub

'
' Parse the command line into its components
'
function ParseCommandLine(iAction, oParamDict)

    on error resume next

    DebugPrint kDebugTrace, L_Text_Dbg_Msg05_Text

    dim oArgs
    dim iIndex

    iAction = kActionUnknown

    set oArgs = Wscript.Arguments

    while iIndex < oArgs.Count

        select case oArgs(iIndex)

            case "-g"
                iAction = kActionGet

            case "-t"
                iAction = kActionSet

            case "-a"
                iAction = kActionAdd

            case "-d"
                iAction = kActionDelete

            case "-l"
                iAction = kActionList

            case "-2e"
                oParamDict.Add kDoubleSpool, true

            case "-2d"
                oParamDict.Add kDoubleSpool, false

            case "-s"
                iIndex = iIndex + 1
                oParamDict.Add kServerName, RemoveBackslashes(oArgs(iIndex))
                
            case "-u"
                iIndex = iIndex + 1
                oParamDict.Add kUserName, oArgs(iIndex)    

            case "-w"
                iIndex = iIndex + 1
                oParamDict.Add kPassword, oArgs(iIndex)
                                    
            case "-n"
                iIndex = iIndex + 1
                oParamDict.Add kPortNumber, oArgs(iIndex)

            case "-r"
                iIndex = iIndex + 1
                oParamDict.Add kPortName, oArgs(iIndex)

            case "-o"
                iIndex = iIndex + 1
                oParamDict.Add kPortType, oArgs(iIndex)

            case "-h"
                iIndex = iIndex + 1
                oParamDict.Add kHostAddress, oArgs(iIndex)

            case "-q"
                iIndex = iIndex + 1
                oParamDict.Add kQueueName, oArgs(iIndex)

            case "-i"
                iIndex = iIndex + 1
                oParamDict.Add kSNMPDeviceIndex, oArgs(iIndex)

            case "-y"
                iIndex = iIndex + 1
                oParamDict.Add kCommunityName, oArgs(iIndex)

            case "-me"
                oParamDict.Add kSNMP, true

            case "-md"
                oParamDict.Add kSNMP, false

            case "-?"
                Usage(True)
                exit function

            case else
                Usage(True)
                exit function

        end select

        iIndex = iIndex + 1

    wend

    if Err = kErrorSuccess then

        ParseCommandLine = kErrorSuccess

    else

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


        ParseCommandLine = kErrorFailure

    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
    wscript.echo L_Help_Help_General18_Text
    wscript.echo L_Help_Help_General19_Text
    wscript.echo L_Help_Help_General20_Text
    wscript.echo L_Help_Help_General21_Text
    wscript.echo L_Help_Help_General22_Text
    wscript.echo L_Empty_Text
    wscript.echo L_Help_Help_General23_Text
    wscript.echo L_Help_Help_General24_Text
    wscript.echo L_Help_Help_General25_Text
    wscript.echo L_Help_Help_General26_Text
    wscript.echo L_Help_Help_General27_Text
    wscript.echo L_Help_Help_General28_Text
    wscript.echo L_Help_Help_General29_Text
    wscript.echo L_Empty_Text
    wscript.echo L_Help_Help_General30_Text
    wscript.echo L_Help_Help_General31_Text
    wscript.echo L_Help_Help_General32_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

'
' Retrieves extended information about the last error that occured 
' during a WBEM operation. The methods that set an SWbemLastError
' object are GetObject, PutInstance, DeleteInstance
'
sub LastError()

    on error resume next

    dim oError

    set oError = CreateObject("WbemScripting.SWbemLastError")
   
    if Err = kErrorSuccess then
   
        wscript.echo L_Operation_Text            & L_Space_Text & oError.Operation
        wscript.echo L_Provider_Text             & L_Space_Text & oError.ProviderName
        wscript.echo L_Description_Text          & L_Space_Text & oError.Description
        wscript.echo L_Text_Error_General04_Text & L_Space_Text & oError.StatusCode
                
    end if                                                             
                                                             
end sub

'
' Connects to the WMI service on a server. oService is returned as a service
' object (SWbemServices)
'
function WmiConnect(strServer, strNameSpace, strUser, strPassword, oService)

   on error resume next

   dim oLocator
   dim bResult
   
   oService = null
   
   bResult  = false
   
   set oLocator = CreateObject("WbemScripting.SWbemLocator")

   if Err = kErrorSuccess then

      set oService = oLocator.ConnectServer(strServer, strNameSpace, strUser, strPassword)

      if Err = kErrorSuccess then

          bResult = true
      
          oService.Security_.impersonationlevel = 3

          '
          ' Required to perform administrative tasks on the spooler service
          '
          oService.Security_.Privileges.AddAsString "SeLoadDriverPrivilege"
          
          Err.Clear
      
      else

          wscript.echo L_Text_Msg_General10_Text & L_Space_Text & L_Error_Text _
                       & L_Space_Text & L_Hex_Text & hex(Err.Number) & L_Space_Text _
                       & Err.Description
            
      end if
   
   else
   
       wscript.echo L_Text_Msg_General09_Text & L_Space_Text & L_Error_Text _
                    & L_Space_Text & L_Hex_Text & hex(Err.Number) & L_Space_Text _
                    & Err.Description
         
   end if                                                         
   
   WmiConnect = bResult
            
end function

'
' Remove leading "\\" from server name
'
function RemoveBackslashes(strServer)

    dim strRet
    
    strRet = strServer
    
    if Left(strServer, 2) = "\\" and Len(strServer) > 2 then 
   
        strRet = Mid(strServer, 3) 
        
    end if   

    RemoveBackslashes = strRet

end function
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
Код:
ShellExecuteWait('prnport.vbs -a -r IP_'&GUICtrlRead($inputbutton)&' -h '&GUICtrlRead($inputbutton)&' -o raw -n 9100')
Run('rundll32 printui.dll,PrintUIEntry /if /b "1522_'&GUICtrlRead($inputbutton)&'" /f hppcp608.inf /r "'&GUICtrlRead($inputbutton)&'" /m "HP LaserJet M1522 MFP Series PCL 6"')

Так попробуй.
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
принес принтер к себе, подключил по TCP/IP, сконвертировал первый скрипт (который прописали)
Код:
GUICreate("Установка сканера HP LJ M1522", 300, 100)
$inputbutton = GUICtrlCreateInput("Введите IP", 50, 20, 100, 20)
$okbutton = GUICtrlCreateButton("OK", 50, 50, 70, 20)
$cancelbutton = GUICtrlCreateButton("Отмена", 180, 50, 70, 20)
GUISetState()
While 1
$msg = GUIGetMsg()
Select
Case $msg = -3 Or $msg = $cancelbutton
ExitLoop
Case $okbutton
If StringLen(GUICtrlRead($inputbutton))=0 Then Exit 1
Run('hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&GUICtrlRead($inputbutton)&'" -n 1')
EndSelect
WEnd

Ввел IP-адресс и нажал ОК, ничего не произошло

Запустил второй скрипт
Код:
ShellExecuteWait('prnport.vbs -a -r IP_'&GUICtrlRead($inputbutton)&' -h '&GUICtrlRead($inputbutton)&' -o raw -n 9100')
Run('rundll32 printui.dll,PrintUIEntry /if /b "1522_'&GUICtrlRead($inputbutton)&'" /f hppcp608.inf /r "'&GUICtrlRead($inputbutton)&'" /m "HP LaserJet M1522 MFP Series PCL 6"')

скопировал в папку где хранится prnport.vbs, выдает ошибку: типа не могу найти путь к prnport.vbs -a -r IP_'&GUICtrlRead($inputbutton)&' -h '&GUICtrlRead($inputbutton)&' -o raw -n 9100. Как понял, windows видит его как полный путь
и начинает копировать драйвера, закрыть приходится только через диспетчер.
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
К hppniscan01.exe и prnport.vbs надо указывать полный путь.
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Спасибо Вам большое!
Завтра попробую, уже пора домой...


Добавлено:
Сообщение автоматически объединено:

Код:
GUICreate("Install scan HP LJ M1522n/nf", 300, 100)
$inputbutton = GUICtrlCreateInput("Введите IP", 50, 20, 100, 20)
$okbutton = GUICtrlCreateButton("OK", 50, 50, 70, 20)
$cancelbutton = GUICtrlCreateButton("Отмена", 180, 50, 70, 20)
$urlbutton = GUICtrlCreateLabel("http://odn.kz", 50, 80, 70, 20)
GUISetState()
While 1
$msg = GUIGetMsg()
Select
Case $msg = -3 Or $msg = $cancelbutton
ExitLoop
Case $okbutton
If StringLen(GUICtrlRead($inputbutton))=0 Then Exit 1
Run('C:\1522_Script_Full_TCP_IP\scaner\hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&GUICtrlRead($inputbutton)&'" -n 1')
EndSelect
WEnd

При запуске exe, сам по себе запускается hppniscan01.exe (несколько копии) :'(
 

sngr

AutoIT Гуру
Сообщения
1,010
Репутация
408
Вместо select здесь надо использовать switch.
Код:
While 1
	$msg = GUIGetMsg()
	Switch $msg
		Case -3
			ExitLoop
		Case $okbutton
			If StringLen(GUICtrlRead($inputbutton))=0 Then Exit 1
			Run('C:\1522_Script_Full_TCP_IP\scaner\hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&GUICtrlRead($inputbutton)&'" -n 1')
		Case $cancelbutton
			ExitLoop
	EndSwitch
WEnd
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
сделал как выше. Запускается hppniscan01.exe только при нажатии на ОК, но не останавливается исполнять команду, пока процесс не убить (установилось 3 копии сканера...).
Можно ли сделать так, убрать команду в RUN-е, а добавить туда запуск bat-файла, которой находится в корне папки, но изменить пункт в bat-файле, который указываем в $inputbutton :blink:
Просто у нас драйвера хранятся на удаленной машине :-[
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Как это понимать? Что делает hppniscan01.exe?
При нажатии на ОК запускается hppniscan01.exe, но даже после установки сканера, он дальше продолжает устанавливать (в Сканерах/факсах появляются несколько копии сканера) пока процесс hppniscan01.exe не убить...
 

Yuri

AutoIT Гуру
Сообщения
737
Репутация
282
daradan
убрать команду в RUN-е, а добавить туда запуск bat-файла
Как-то примерно так
Код:
#include <GuiIPAddress.au3>
$Form1 = GUICreate("Install scan HP LJ M1522n/nf", 300, 100)
GUICtrlCreateLabel("Введите IP", 50, 5, 100, 20)
$IPAddress = _GUICtrlIpAddress_Create($Form1, 50, 20, 100, 20)
$okbutton = GUICtrlCreateButton("OK", 50, 50, 70, 20)
$cancelbutton = GUICtrlCreateButton("Отмена", 180, 50, 70, 20)
$urlbutton = GUICtrlCreateLabel("http://odn.kz", 50, 80, 70, 20)
GUISetState()
While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case -3
            ExitLoop
		 Case $okbutton
            $IP = _GUICtrlIpAddress_Get($IPAddress)            
			WriteRunCMD($IP)
		 Case $urlbutton 			
            ShellExecute("http://odn.kz")
        Case $cancelbutton
            ExitLoop
    EndSwitch
WEnd

Func WriteRunCMD($IP)
   $File = "Setup.cmd"
   $hFile = FileOpen($File, 2)
   $Command = 'C:\1522_Script_Full_TCP_IP\scaner\hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&$IP&'" -n 1'&@CRLF&'pause'
   FileWrite($hFile, $Command)
   FileClose($hFile)
   ShellExecute($File)
   Return
EndFunc
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Как-то примерно так

Спасибо, скрипт работает даже если удалить полный путь (удалил C:\1522_Script_Full_TCP_IP\scaner\), главное чтоб был в корне папки. Но все равно скрипт не заканчивает выполнять команду и устанавливаются опять же несколько копии сканера :'(
 

Yuri

AutoIT Гуру
Сообщения
737
Репутация
282
скрипт не заканчивает выполнять команду
Странно. Скрипт Autoit тут не причем как бы.
Его работа при нажатии кнопки Ок:
Прочитать введеный IP
Свормировать строку с этим IP
Создать/открыть файл cmd для перезаписи
Записать эту строку
Закрыть этот файл
Запустить получившийся батник
Ожидать дальнейших указаний

P.S.
Вот если заменить строку
Код:
$Command = 'C:\1522_Script_Full_TCP_IP\scaner\hppniscan01.exe -f "hppasc08.inf" -m "vid_03f0&pid_4C17&IP_SCAN" -a "'&$IP&'" -n 1'&@CRLF&'pause'

На эту
Код:
$Command = 'ping '&$IP&@CRLF&'pause'

Тоже три раза сработает?
 
Автор
D

daradan

Новичок
Сообщения
13
Репутация
0
Заменил строку. При нажатии ОК, открывается cmd и пингует тот IP который указал, после пишет "Для продолжения нажмите любую клавишу . . ."
Тоже три раза сработает?
не понял
 

Yuri

AutoIT Гуру
Сообщения
737
Репутация
282
Имелось в виду что батник отработает один раз,
а не несколько, и скрипт AutoIt не будет сам запускать
этот батник повторно, пока опять не нажмешь на кнопку Ок.
Значит сам скрипт работает корректно.
Вот без паузы
Код:
$Command = 'ping '&$IP
 
Верх