Jump to content

Recommended Posts

Hi everyone.Need rewrite this function how in еxample.

Original:

#RequireAdmin
#NoTrayIcon
Opt("MustDeclareVars",1)

Func _a()
Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _
&"authenticationLevel=Pkt}!\\"& _
@ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _
('SELECT * FROM WmiMonitorID'), _
$lll,$sll,$sss="",$lsl,$lls,$i,$z
For $z In $lss
$lsl=$z.UserFriendlyName
For $i=0 To Ubound($lsl)-1
if ($lsl[$i]) Then $lll&=Chr($lsl[$i])
Next
$lls=$z.SerialNumberID
For $i=0 To Ubound($lls)-1
if ($lls[$i]) Then $sll&=Chr($lls[$i])
Next
$sss&="Model"&@TAB&@TAB&":   "&$lll&@CR&"Serial Number"&@TAB&":   "&$sll&@CR&@CR
$lll=""
$sll=""
Next
MsgBox(262144,'Monitors   '&$lss.Count,$sss&" "&@CR)
$lss=Null
$sls=Null
EndFunc
_a()

Example:

Func _InfoPC()
    Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2')
    Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30)
     If IsObj($ObjService) Then
       For $objItemMB In $ObjMB
            $sInfo &= @TAB & 'Motherboard: ...... ' & $objItemMB.Product & @CRLF

I'm beginner in this sphere and need  you all speak easy and simply because i'm Russian.Thanks)

Edited by DirtyJohny
Link to post
Share on other sites
  • Moderators

Moved to the appropriate forum, as the Developer General Discussion forum very clearly states:

Quote

General development and scripting discussions.


Do not create AutoIt-related topics here, use the AutoIt General Help and Support or AutoIt Technical Discussion forums.

Moderation Team

Edited by JLogan3o13

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to post
Share on other sites

Please search the forum for "Scriptomatic". This tool creates AutoIt scripts to query WMI for you.

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2021-06-05 - Version 1.5.4.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2021-06-14 - Version 1.6.5.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Link to post
Share on other sites

Run the script and wait until the "please wait" messages in WMI namespace and WMI class have disappeared. Then select the Win32_DesktopMonitor class and click "Run".

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2021-06-05 - Version 1.5.4.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2021-06-14 - Version 1.6.5.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Link to post
Share on other sites
4 hours ago, Nine said:

Not all environments support "WmiMonitorID",  use instead "Win32_DesktopMonitor".

I see the class Win32_DesktopMonitor, but you must know in this class not show Serial nubmber and model, check please. And this function must work in autoit.See more in this link "https://docs.microsoft.com/en-us/windows/win32/wmicoreprov/wmimonitorid".Now i have a trying  rewrite  but unfinished...

Edited by DirtyJohny
Link to post
Share on other sites
4 hours ago, water said:

Run the script and wait until the "please wait" messages in WMI namespace and WMI class have disappeared. Then select the Win32_DesktopMonitor class and click "Run".

I not see the MonitorID...I just want see serial numbers and models and how i know, others classes "Monitor" not show this information. Is it really impossible rewrite this script, when this script working? I need rewrite form how i see it in example....And I need help in this

Edited by DirtyJohny
Link to post
Share on other sites
  • Moderators

@DirtyJohny Just because this is the most important thing in the world to you does not mean you need to post every 10 minutes. Please follow the forum etiquette and wait at least 24 hours before bumping your thread. You could use that time to do some research on your own.

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to post
Share on other sites

 

9 minutes ago, JLogan3o13 said:

@DirtyJohny Just because this is the most important thing in the world to you does not mean you need to post every 10 minutes. Please follow the forum etiquette and wait at least 24 hours before bumping your thread. You could use that time to do some research on your own.

I just answered, not see problem.I edit my messages because my english not very good and I think, based on etiquette, it would be better to speak clearly so that I can be understood.But thanks for the advice.

Link to post
Share on other sites

@DirtyJohny

Since this is not as simple as it seems because some of the WMIMonitorID class properties are byte arrays that need to be converted to strings, I thought I would help you out.  Below is one way that you can grab the property values.

#AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d

#include <Constants.au3>

example()

Func example()
    Local $oComErr, $oWmi, $oInstances

    $oComErr = ObjEvent("AutoIt.Error", com_error_handler)
    #forceref $oComErr

    ;Get WMI object
    $oWmi = ObjGet("winmgmts:\root\WMI")
    If Not IsObj($oWmi) Then Exit MsgBox($MB_ICONERROR, "ERROR", "Unable to create WMI object")

    ;Select object instances
    $oInstances = $oWmi.ExecQuery("SELECT * FROM WMIMonitorID")
    If $oInstances.Count = 0 Then Exit MsgBox($MB_ICONWARNING,"Warning","No objects found")

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            ConsoleWrite("InstanceName      = " & .InstanceName      & @CRLF)
            ConsoleWrite("YearOfManufacture = " & .YearOfManufacture & @CRLF)
            ConsoleWrite("WeekOfManufacture = " & .WeekOfManufacture & @CRLF)

            If IsArray(.UserFriendlyName) Then ConsoleWrite("UserFriendlyName  = " & convert_int_array_to_string(.UserFriendlyName) & @CRLF)
            If IsArray(.ManufacturerName) Then ConsoleWrite("ManufacturerName  = " & convert_int_array_to_string(.ManufacturerName) & @CRLF)
            If IsArray(.SerialNumberId)   Then ConsoleWrite("SerialNumberId    = " & convert_int_array_to_string(.SerialNumberId)   & @CRLF)
            If IsArray(.ProductCodeID)    Then ConsoleWrite("ProductCodeID     = " & convert_int_array_to_string(.ProductCodeID)    & @CRLF)
        EndWith
    Next
EndFunc

Func convert_int_array_to_string($aUInts)
    Local $s  = ""

    For $i = 0 To UBound($aUInts) - 1
        If $aUInts[$i] = 0 Then ExitLoop
        $s &= Chr($aUInts[$i])
    Next

    Return $s
EndFunc

Func com_error_handler($oComError)
    ConsoleWrite(@CRLF)
    ConsoleWrite(StringFormat("Script Line  = %s", $oComError.ScriptLine) & @CRLF)
    ConsoleWrite(StringFormat("Win Err Desc = %s", StringStripWS($oComError.WinDescription, $STR_STRIPTRAILING)) & @CRLF)
    ConsoleWrite(StringFormat("Error Number = %i (0x%x)", $oComError.Number, $oComError.Number) & @CRLF)
    ConsoleWrite(StringFormat("Error Desc   = %s", $oComError.Description) & @CRLF)
    Exit
EndFunc

Example Output:

InstanceName           = DISPLAY\HWP293A\5&294a6614&0&UID1048849_0
YearOfManufacture      = 2012
WeekOfManufacture      = 46
UserFriendlyName       = HP 2311x
ManufacturerName       = HWP
SerialNumberId         = 3CQ24628ZX
ProductCodeID          = 293A

 

Edited by TheXman
Link to post
Share on other sites

 Thank you so much) And i correct your script see that 

#AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d

#include <Constants.au3>
#include <Array.au3>

example()

Func example()
    Local $oComErr, $oWmi, $oInstances

    $oComErr = ObjEvent("AutoIt.Error", comm_error_handler)
    #forceref $oComErr

    ;Get WMI object
    $oWmi = ObjGet("winmgmts:\root\WMI")
    If Not IsObj($oWmi) Then Exit MsgBox($MB_ICONERROR, "ERROR", "Unable to create WMI object")

    ;Select object instances
    $oInstances = $oWmi.ExecQuery("SELECT * FROM WMIMonitorID")
    If $oInstances.Count = 0 Then Exit MsgBox($MB_ICONWARNING,"Warning","No objects found")

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then ConsoleWrite(StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName)) & @CRLF)
            If IsArray(.SerialNumberId)   Then ConsoleWrite(StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId)) & @CRLF)

        EndWith
    Next
EndFunc

Func convert_uint16_array_to_string($aBytes)
    Local $s  = ""

    For $i in $aBytes
        If $i <> 0 Then $s &= Chr($i)
    Next

    Return $s
EndFunc

Func comm_error_handler($oComError)
    ConsoleWrite(@CRLF)
    ConsoleWrite(StringFormat("Script Line  = %s", $oComError.ScriptLine) & @CRLF)
    ConsoleWrite(StringFormat("Win Err Desc = %s", StringStripWS($oComError.WinDescription, $STR_STRIPTRAILING)) & @CRLF)
    ConsoleWrite(StringFormat("Error Number = %i (0x%x)", $oComError.Number, $oComError.Number) & @CRLF)
    ConsoleWrite(StringFormat("Error Desc   = %s", $oComError.Description) & @CRLF)
    Exit
EndFunc

 

Edited by DirtyJohny
Link to post
Share on other sites

And next question how i insert all this in my script?( I heve no idea(

#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <ButtonConstants.au3>
#RequireAdmin
#NoTrayIcon

;Все что написано, посде ';' явлется комментарием и ни как не влияет на работу скрипта.

Global $iKabina, $iType, $iKabina, $iModel, $iSerialNum, $iInv ;объявляем переменные, которые будут использоваться в цикле
Global $rKabina, $rType, $rModel, $rSerialNum, $rInv, $Main, $iConnect, $hFile, $sInfo, $CopyBtn, $fFile = @ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt"

$Main = GUICreate('Инвентаризация', 315, 352) ;рисуем главное окно
GUISetBkColor(0x02101B)

$iKabina = GUICtrlCreateInput('', 20, 30, 272, 21)
$iType = GUICtrlCreateInput('', 20, 75, 272, 21)
$iModel = GUICtrlCreateInput('', 20, 120, 272, 21)
$iSerialNum = GUICtrlCreateInput('', 20, 165, 272, 21)
$iInv = GUICtrlCreateInput('', 20, 210, 272, 21)

GUISetFont(10, 800, 0, 'Tahoma'); Устанавливает шрифт по умолчанию для последующих элементов GUI-окна.
$iConnect = GUICtrlCreateButton('Передать', 23, 305, 267, 33, $BS_DEFPUSHBUTTON) ;создаем кнопку подключения

GUICtrlSetDefColor(0xDEDEDE); Устанавливает цвет текста по умолчанию для последующих элементов GUI-окна.
GUICtrlCreateLabel('Кабинет', 20, 10, 150, 17)
GUICtrlCreateLabel('Тип', 20, 55, 150, 17)
GUICtrlCreateLabel('Модель', 20, 100, 150, 17)
GUICtrlCreateLabel('Серийный номер', 20, 145, 150, 17)
GUICtrlCreateLabel('Инвентарник', 20, 190, 150, 17)

WinSetTrans($Main, '', 0)
GUISetState(@SW_SHOW)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Main, '', $i) ;Прозрачность 0-255
Next

$hFile = FileOpen(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", 1)

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $iConnect
            $rKabina = GUICtrlRead($iKabina)
            $rType = GUICtrlRead($iType)
            $rModel = GUICtrlRead($iModel)
            $rSerialNum = GUICtrlRead($iSerialNum)
            $rInv = GUICtrlRead($iInv)

            Select
                Case (Not StringStripWS($rKabina, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Кабинет - пустое')
                Case (Not StringStripWS($rType, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Тип - пустое')
                Case (Not StringStripWS($rModel, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Модель - пустое')
                Case (Not StringStripWS($rSerialNum, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Серийный номер - пустое')
                Case (Not StringStripWS($rInv, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Инвентарник - пустое')
                Case $hFile = -1
                    MsgBox(4096, 'Ошибка', 'Невозможно открыть файл.')
                Case Else
                    _hide() ;отключает все элементы ввода и кнопку
                    $sInfo = '======================================================================================' & @CRLF & _
                                   '[МЕСТОПОЛОЖЕНИЕ:]' & @CRLF & _
                            @TAB & 'Дата: ................... ' & @MDAY & '.' & @MON & '.' & @YEAR & ' ' & @CRLF & _
                            @TAB & 'Кабинет: ................ ' & $rKabina & @CRLF & _
                            @TAB & 'Тип: .................... ' & $rType & @CRLF & _
                            @TAB & 'Модель: ................. ' & $rModel & @CRLF & _
                            @TAB & 'Серийный номер: ......... ' & $rSerialNum & @CRLF & _
                            @TAB & 'Инвентарный номер: ...... ' & $rInv & @CRLF & _
                            @TAB & 'Учетная запись: ......... ' & @UserName & @CRLF & @CRLF
                    $sInfo &= _InfoPC()
                    FileWrite($hFile, $sInfo)
                    FileClose($hFile)
                    _show() ;включает все элементы ввода и кнопку
                    _ShowOtchot()
            EndSelect
    EndSwitch
WEnd



Func _InfoPC()
    Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2')
    Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30)
    Local $ObjProcessor = $ObjService.ExecQuery('SELECT * FROM Win32_Processor', 'WQL', 0x30)
    Local $ObjMemory = $ObjService.ExecQuery('SELECT * FROM Win32_PhysicalMemory')
    Local $ObjNet = $ObjService.ExecQuery('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x30)
    Local $ObjGraph = $ObjService.ExecQuery('SELECT * FROM Win32_VideoController', 'WQL', 0x30)
    Local $ObjDrive = $ObjService.ExecQuery('SELECT * FROM Win32_DiskDrive', 'WQL', 0x30)
    Local $ObjCDDrive = $ObjService.ExecQuery('SELECT * FROM Win32_CDROMDrive', 'WQL', 0x30)
    Local $ObjRam = $ObjService.ExecQuery('SELECT * FROM Win32_ComputerSystem')
    Local $sNameComput = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0', 'szTargetName')
    Local $sProduct = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName')
    Local $sBuild = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ReleaseId')

    Local $sItemM, $sInfo = '[КОНФИГУРАЦИЯ:]' & @CRLF & @TAB & 'Имя компьютера: ......... ' & $sNameComput & @CRLF & _
            @TAB & 'Операционная система: ... ' & $sProduct & ' ' & $sBuild & ' ' & '(' & @OSArch & ')' & @CRLF

    If IsObj($ObjService) Then
        For $objItemP In $ObjProcessor
            $sInfo &= @TAB & 'Процессор: .............. ' & $objItemP.Name & @CRLF
        Next
        For $objItemMB In $ObjMB
            $sInfo &= @TAB & 'Материнская плата: ...... ' & $objItemMB.Product & @CRLF
        Next
        For $ObjItemM In $ObjMemory
            $sItemM = $objItemM.Speed
        Next
        For $objItemR In $ObjRam
            $sInfo &= @TAB & 'RAM: .................... ' & Round($objItemR.TotalPhysicalMemory / 1024 / 1024 ^ 2, 0) & ' GB | ' & $ObjMemory.Count & ' pieces | ' & $sItemM & ' Mhz' & @CRLF
        Next
        For $ObjItemG In $ObjGraph
            $sInfo &= @TAB & 'Видеокарта: ............. ' & $ObjItemG.Name & ' | RAM: ' & $ObjItemG.AdapterRAM / 1024 ^ 2 & ' Mb' & @CRLF
        Next
        For $ObjItemD In $ObjDrive
            $sInfo &= @TAB & 'Жесткие диск: ........... ' & $ObjItemD.Model & ' | Size: ' & Round($ObjItemD.Size / 1024 / 1024 / 1024) & ' Gb' & @CRLF
        Next
        For $ObjItemCD In $ObjCDDrive
            $sInfo &= @TAB & 'Дисковод: ............... ' & $ObjItemCD.Name & @CRLF
        Next
        For $ObjItemN In $ObjNet
            If $ObjItemN.PhysicalAdapter = True Then
                $sInfo &= @TAB & 'Сетевой адаптер: ........ ' & $ObjItemN.Name & @CRLF
            EndIf
        Next
    EndIf
    $sInfo &= @CRLF

    Return $sInfo
EndFunc   ;==>_InfoPC

Func _hide() ;функция. отключает элементы ввода и кнопку, пока работает скрипт
    GUICtrlSetState($iConnect, $GUI_disable)
    GUICtrlSetState($iKabina, $GUI_disable)
    GUICtrlSetState($iType, $GUI_disable)
    GUICtrlSetState($iModel, $GUI_disable)
    GUICtrlSetState($iSerialNum, $GUI_disable)
    GUICtrlSetState($iInv, $GUI_disable)
EndFunc   ;==>_hide

Func _show() ;функция. включает элементы ввода и кнопку, когда скрипт отработал
    GUICtrlSetState($iConnect, $GUI_enable)
    GUICtrlSetState($iKabina, $GUI_enable)
    GUICtrlSetState($iType, $GUI_enable)
    GUICtrlSetState($iModel, $GUI_enable)
    GUICtrlSetState($iSerialNum, $GUI_enable)
    GUICtrlSetState($iInv, $GUI_enable)
 EndFunc   ;==>_show

Opt("MustDeclareVars",1)

Func _a()
Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _
&"authenticationLevel=Pkt}!\\"& _
@ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _
('SELECT * FROM WmiMonitorID'), _
$lll,$sll,$sss="",$lsl,$lls,$i,$z
For $z In $lss
$lsl=$z.UserFriendlyName
For $i=0 To Ubound($lsl)-1
if ($lsl[$i]) Then $lll&=Chr($lsl[$i])
Next
$lls=$z.SerialNumberID
For $i=0 To Ubound($lls)-1
if ($lls[$i]) Then $sll&=Chr($lls[$i])
Next
$sss&="Model"&@TAB&@TAB&":   "&$lll&@CR&"Serial Number"&@TAB&":   "&$sll&@CR&@CR
$lll=""
$sll=""
Next

$lss=Null
$sls=Null
 $sInfo &= @CRLF
EndFunc

 Func _ShowOtchot()
    $Form1 = GUICreate("Отчёт", 482, 438, Default, Default, Default, 0x00000080, $Main)
    GUISetBkColor(0x02101B)
    $Edit1 = GUICtrlCreateEdit("", 0, 0, 482, 385)
    GUICtrlSetData(-1, FileRead($fFile))
    $CopyBtn = GUICtrlCreateButton("Копировать", 194, 400, 99, 25, $BS_DEFPUSHBUTTON)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Form1, '', $i) ;Прозрачность 0-255
Next
    GUISetState(@SW_SHOW)
    While 1
        $msg = GUIGetMsg()
        Switch $msg
            Case $CopyBtn
                ClipPut(GUICtrlRead($Edit1))
                DirCreate (@ScriptDir & "\COPY")
                FileCopy(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", @ScriptDir & "\COPY", 1)
                MsgBox(64, "Статус", 'Скопировано', Default, $Main)
            Case -3
                GUIDelete($Form1)
                WinActivate($Main)
                ExitLoop
        EndSwitch
    WEnd
EndFunc

 

Link to post
Share on other sites

Hey, you could incorporate the example script like this:

I hope this will be clear :) 

copy paste func example() and other functions needed to your script, and change: func example() to a more meaningful name, say, func Display_Info()

Then in your script:

(Local/Global) $aDisplayInfo = Display_Info()

 

and change func Display_Info() as such that instead of consolewriting, add what you want returned to an array, say, $aReturn, at this part

Local $aReturn[2] ; change number if you want to return more info

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then $aReturn[0] = StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName))
            If IsArray(.SerialNumberId)   Then $aReturn[1] = StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId))
        EndWith
    Next
    
    Return $aReturn

and at the end of func Display_Info()  add this line

Return $aReturn

 

Now, in your script use $aDisplayInfo[0] for UserFriendlyName, or $aDisplayInfo[1] for SerialNumberId

Also, check if returned is an array before using it in your script, like:

if $aDisplayInfo = "" then

 Exit/msgbox/skip this part/whatever you want to do

endif

Link to post
Share on other sites
1 hour ago, GokAy said:

Hey, you could incorporate the example script like this:

I hope this will be clear :) 

copy paste func example() and other functions needed to your script, and change: func example() to a more meaningful name, say, func Display_Info()

Then in your script:

(Local/Global) $aDisplayInfo = Display_Info()

 

and change func Display_Info() as such that instead of consolewriting, add what you want returned to an array, say, $aReturn, at this part

Local $aReturn[2] ; change number if you want to return more info

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then $aReturn[0] = StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName))
            If IsArray(.SerialNumberId)   Then $aReturn[1] = StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId))
        EndWith
    Next
    
    Return $aReturn

and at the end of func Display_Info()  add this line

Return $aReturn

 

Now, in your script use $aDisplayInfo[0] for UserFriendlyName, or $aDisplayInfo[1] for SerialNumberId

Also, check if returned is an array before using it in your script, like:

if $aDisplayInfo = "" then

 Exit/msgbox/skip this part/whatever you want to do

endif

Thanks)Sorry dont  understand how it should look....

Edited by DirtyJohny
Link to post
Share on other sites

Where do you want the information for display in your script? I can't decipher it :) 

Your script should be like this, but need to add:

(Local/Global) $aDisplayInfo = Display_Info()

somewhere. And then read what is returned from the array after checking if it is an array. Empty string would mean, the query was unsuccessful I guess.

Note: I can read cyrillic alphabet and understand some of the words in Russian especially if technical, however, I don't know where you would like to access the information within your script.

Untested!

#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <ButtonConstants.au3>

#include <Constants.au3>
#include <Array.au3>

#RequireAdmin
#NoTrayIcon

;Все что написано, посде ';' явлется комментарием и ни как не влияет на работу скрипта.

Global $iKabina, $iType, $iKabina, $iModel, $iSerialNum, $iInv ;объявляем переменные, которые будут использоваться в цикле
Global $rKabina, $rType, $rModel, $rSerialNum, $rInv, $Main, $iConnect, $hFile, $sInfo, $CopyBtn, $fFile = @ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt"

$Main = GUICreate('Инвентаризация', 315, 352) ;рисуем главное окно
GUISetBkColor(0x02101B)

$iKabina = GUICtrlCreateInput('', 20, 30, 272, 21)
$iType = GUICtrlCreateInput('', 20, 75, 272, 21)
$iModel = GUICtrlCreateInput('', 20, 120, 272, 21)
$iSerialNum = GUICtrlCreateInput('', 20, 165, 272, 21)
$iInv = GUICtrlCreateInput('', 20, 210, 272, 21)

GUISetFont(10, 800, 0, 'Tahoma'); Устанавливает шрифт по умолчанию для последующих элементов GUI-окна.
$iConnect = GUICtrlCreateButton('Передать', 23, 305, 267, 33, $BS_DEFPUSHBUTTON) ;создаем кнопку подключения

GUICtrlSetDefColor(0xDEDEDE); Устанавливает цвет текста по умолчанию для последующих элементов GUI-окна.
GUICtrlCreateLabel('Кабинет', 20, 10, 150, 17)
GUICtrlCreateLabel('Тип', 20, 55, 150, 17)
GUICtrlCreateLabel('Модель', 20, 100, 150, 17)
GUICtrlCreateLabel('Серийный номер', 20, 145, 150, 17)
GUICtrlCreateLabel('Инвентарник', 20, 190, 150, 17)

WinSetTrans($Main, '', 0)
GUISetState(@SW_SHOW)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Main, '', $i) ;Прозрачность 0-255
Next

$hFile = FileOpen(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", 1)

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $iConnect
            $rKabina = GUICtrlRead($iKabina)
            $rType = GUICtrlRead($iType)
            $rModel = GUICtrlRead($iModel)
            $rSerialNum = GUICtrlRead($iSerialNum)
            $rInv = GUICtrlRead($iInv)

            Select
                Case (Not StringStripWS($rKabina, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Кабинет - пустое')
                Case (Not StringStripWS($rType, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Тип - пустое')
                Case (Not StringStripWS($rModel, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Модель - пустое')
                Case (Not StringStripWS($rSerialNum, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Серийный номер - пустое')
                Case (Not StringStripWS($rInv, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Инвентарник - пустое')
                Case $hFile = -1
                    MsgBox(4096, 'Ошибка', 'Невозможно открыть файл.')
                Case Else
                    _hide() ;отключает все элементы ввода и кнопку
                    $sInfo = '======================================================================================' & @CRLF & _
                                   '[МЕСТОПОЛОЖЕНИЕ:]' & @CRLF & _
                            @TAB & 'Дата: ................... ' & @MDAY & '.' & @MON & '.' & @YEAR & ' ' & @CRLF & _
                            @TAB & 'Кабинет: ................ ' & $rKabina & @CRLF & _
                            @TAB & 'Тип: .................... ' & $rType & @CRLF & _
                            @TAB & 'Модель: ................. ' & $rModel & @CRLF & _
                            @TAB & 'Серийный номер: ......... ' & $rSerialNum & @CRLF & _
                            @TAB & 'Инвентарный номер: ...... ' & $rInv & @CRLF & _
                            @TAB & 'Учетная запись: ......... ' & @UserName & @CRLF & @CRLF
                    $sInfo &= _InfoPC()
                    FileWrite($hFile, $sInfo)
                    FileClose($hFile)
                    _show() ;включает все элементы ввода и кнопку
                    _ShowOtchot()
            EndSelect
    EndSwitch
WEnd



Func _InfoPC()
    Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2')
    Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30)
    Local $ObjProcessor = $ObjService.ExecQuery('SELECT * FROM Win32_Processor', 'WQL', 0x30)
    Local $ObjMemory = $ObjService.ExecQuery('SELECT * FROM Win32_PhysicalMemory')
    Local $ObjNet = $ObjService.ExecQuery('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x30)
    Local $ObjGraph = $ObjService.ExecQuery('SELECT * FROM Win32_VideoController', 'WQL', 0x30)
    Local $ObjDrive = $ObjService.ExecQuery('SELECT * FROM Win32_DiskDrive', 'WQL', 0x30)
    Local $ObjCDDrive = $ObjService.ExecQuery('SELECT * FROM Win32_CDROMDrive', 'WQL', 0x30)
    Local $ObjRam = $ObjService.ExecQuery('SELECT * FROM Win32_ComputerSystem')
    Local $sNameComput = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0', 'szTargetName')
    Local $sProduct = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName')
    Local $sBuild = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ReleaseId')

    Local $sItemM, $sInfo = '[КОНФИГУРАЦИЯ:]' & @CRLF & @TAB & 'Имя компьютера: ......... ' & $sNameComput & @CRLF & _
            @TAB & 'Операционная система: ... ' & $sProduct & ' ' & $sBuild & ' ' & '(' & @OSArch & ')' & @CRLF

    If IsObj($ObjService) Then
        For $objItemP In $ObjProcessor
            $sInfo &= @TAB & 'Процессор: .............. ' & $objItemP.Name & @CRLF
        Next
        For $objItemMB In $ObjMB
            $sInfo &= @TAB & 'Материнская плата: ...... ' & $objItemMB.Product & @CRLF
        Next
        For $ObjItemM In $ObjMemory
            $sItemM = $objItemM.Speed
        Next
        For $objItemR In $ObjRam
            $sInfo &= @TAB & 'RAM: .................... ' & Round($objItemR.TotalPhysicalMemory / 1024 / 1024 ^ 2, 0) & ' GB | ' & $ObjMemory.Count & ' pieces | ' & $sItemM & ' Mhz' & @CRLF
        Next
        For $ObjItemG In $ObjGraph
            $sInfo &= @TAB & 'Видеокарта: ............. ' & $ObjItemG.Name & ' | RAM: ' & $ObjItemG.AdapterRAM / 1024 ^ 2 & ' Mb' & @CRLF
        Next
        For $ObjItemD In $ObjDrive
            $sInfo &= @TAB & 'Жесткие диск: ........... ' & $ObjItemD.Model & ' | Size: ' & Round($ObjItemD.Size / 1024 / 1024 / 1024) & ' Gb' & @CRLF
        Next
        For $ObjItemCD In $ObjCDDrive
            $sInfo &= @TAB & 'Дисковод: ............... ' & $ObjItemCD.Name & @CRLF
        Next
        For $ObjItemN In $ObjNet
            If $ObjItemN.PhysicalAdapter = True Then
                $sInfo &= @TAB & 'Сетевой адаптер: ........ ' & $ObjItemN.Name & @CRLF
            EndIf
        Next
    EndIf
    $sInfo &= @CRLF

    Return $sInfo
EndFunc   ;==>_InfoPC

Func _hide() ;функция. отключает элементы ввода и кнопку, пока работает скрипт
    GUICtrlSetState($iConnect, $GUI_disable)
    GUICtrlSetState($iKabina, $GUI_disable)
    GUICtrlSetState($iType, $GUI_disable)
    GUICtrlSetState($iModel, $GUI_disable)
    GUICtrlSetState($iSerialNum, $GUI_disable)
    GUICtrlSetState($iInv, $GUI_disable)
EndFunc   ;==>_hide

Func _show() ;функция. включает элементы ввода и кнопку, когда скрипт отработал
    GUICtrlSetState($iConnect, $GUI_enable)
    GUICtrlSetState($iKabina, $GUI_enable)
    GUICtrlSetState($iType, $GUI_enable)
    GUICtrlSetState($iModel, $GUI_enable)
    GUICtrlSetState($iSerialNum, $GUI_enable)
    GUICtrlSetState($iInv, $GUI_enable)
 EndFunc   ;==>_show

Opt("MustDeclareVars",1)

Func _a()
Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _
&"authenticationLevel=Pkt}!\\"& _
@ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _
('SELECT * FROM WmiMonitorID'), _
$lll,$sll,$sss="",$lsl,$lls,$i,$z
For $z In $lss
$lsl=$z.UserFriendlyName
For $i=0 To Ubound($lsl)-1
if ($lsl[$i]) Then $lll&=Chr($lsl[$i])
Next
$lls=$z.SerialNumberID
For $i=0 To Ubound($lls)-1
if ($lls[$i]) Then $sll&=Chr($lls[$i])
Next
$sss&="Model"&@TAB&@TAB&":   "&$lll&@CR&"Serial Number"&@TAB&":   "&$sll&@CR&@CR
$lll=""
$sll=""
Next

$lss=Null
$sls=Null
 $sInfo &= @CRLF
EndFunc

 Func _ShowOtchot()
    $Form1 = GUICreate("Отчёт", 482, 438, Default, Default, Default, 0x00000080, $Main)
    GUISetBkColor(0x02101B)
    $Edit1 = GUICtrlCreateEdit("", 0, 0, 482, 385)
    GUICtrlSetData(-1, FileRead($fFile))
    $CopyBtn = GUICtrlCreateButton("Копировать", 194, 400, 99, 25, $BS_DEFPUSHBUTTON)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Form1, '', $i) ;Прозрачность 0-255
Next
    GUISetState(@SW_SHOW)
    While 1
        $msg = GUIGetMsg()
        Switch $msg
            Case $CopyBtn
                ClipPut(GUICtrlRead($Edit1))
                DirCreate (@ScriptDir & "\COPY")
                FileCopy(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", @ScriptDir & "\COPY", 1)
                MsgBox(64, "Статус", 'Скопировано', Default, $Main)
            Case -3
                GUIDelete($Form1)
                WinActivate($Main)
                ExitLoop
        EndSwitch
    WEnd
EndFunc

Func Display_Info()
    Local $oComErr, $oWmi, $oInstances

    $oComErr = ObjEvent("AutoIt.Error", comm_error_handler)
    #forceref $oComErr

    ;Get WMI object
    $oWmi = ObjGet("winmgmts:\root\WMI")
    If Not IsObj($oWmi) Then Exit MsgBox($MB_ICONERROR, "ERROR", "Unable to create WMI object")

    ;Select object instances
    $oInstances = $oWmi.ExecQuery("SELECT * FROM WMIMonitorID")
    If $oInstances.Count = 0 Then Exit MsgBox($MB_ICONWARNING,"Warning","No objects found")
    
    ; Changed part
    Local $aReturn[2] ; change number if you want to return more info

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then $aReturn[0] = StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName))
            If IsArray(.SerialNumberId)   Then $aReturn[1] = StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId))
        EndWith
    Next
    
    Return $aReturn
    
EndFunc

Func convert_uint16_array_to_string($aBytes)
    Local $s  = ""

    For $i in $aBytes
        If $i <> 0 Then $s &= Chr($i)
    Next

    Return $s
EndFunc

Func comm_error_handler($oComError)
    ConsoleWrite(@CRLF)
    ConsoleWrite(StringFormat("Script Line  = %s", $oComError.ScriptLine) & @CRLF)
    ConsoleWrite(StringFormat("Win Err Desc = %s", StringStripWS($oComError.WinDescription, $STR_STRIPTRAILING)) & @CRLF)
    ConsoleWrite(StringFormat("Error Number = %i (0x%x)", $oComError.Number, $oComError.Number) & @CRLF)
    ConsoleWrite(StringFormat("Error Desc   = %s", $oComError.Description) & @CRLF)
    Exit
EndFunc
Link to post
Share on other sites
4 minutes ago, GokAy said:

Where do you want the information for display in your script? I can't decipher it :) 

Your script should be like this, but need to add:

(Local/Global) $aDisplayInfo = Display_Info()

somewhere. And then read what is returned from the array after checking if it is an array. Empty string would mean, the query was unsuccessful I guess.

Note: I can read cyrillic alphabet and understand some of the words in Russian especially if technical, however, I don't know where you would like to access the information within your script.

Untested!

#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <ButtonConstants.au3>

#include <Constants.au3>
#include <Array.au3>

#RequireAdmin
#NoTrayIcon

;Все что написано, посде ';' явлется комментарием и ни как не влияет на работу скрипта.

Global $iKabina, $iType, $iKabina, $iModel, $iSerialNum, $iInv ;объявляем переменные, которые будут использоваться в цикле
Global $rKabina, $rType, $rModel, $rSerialNum, $rInv, $Main, $iConnect, $hFile, $sInfo, $CopyBtn, $fFile = @ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt"

$Main = GUICreate('Инвентаризация', 315, 352) ;рисуем главное окно
GUISetBkColor(0x02101B)

$iKabina = GUICtrlCreateInput('', 20, 30, 272, 21)
$iType = GUICtrlCreateInput('', 20, 75, 272, 21)
$iModel = GUICtrlCreateInput('', 20, 120, 272, 21)
$iSerialNum = GUICtrlCreateInput('', 20, 165, 272, 21)
$iInv = GUICtrlCreateInput('', 20, 210, 272, 21)

GUISetFont(10, 800, 0, 'Tahoma'); Устанавливает шрифт по умолчанию для последующих элементов GUI-окна.
$iConnect = GUICtrlCreateButton('Передать', 23, 305, 267, 33, $BS_DEFPUSHBUTTON) ;создаем кнопку подключения

GUICtrlSetDefColor(0xDEDEDE); Устанавливает цвет текста по умолчанию для последующих элементов GUI-окна.
GUICtrlCreateLabel('Кабинет', 20, 10, 150, 17)
GUICtrlCreateLabel('Тип', 20, 55, 150, 17)
GUICtrlCreateLabel('Модель', 20, 100, 150, 17)
GUICtrlCreateLabel('Серийный номер', 20, 145, 150, 17)
GUICtrlCreateLabel('Инвентарник', 20, 190, 150, 17)

WinSetTrans($Main, '', 0)
GUISetState(@SW_SHOW)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Main, '', $i) ;Прозрачность 0-255
Next

$hFile = FileOpen(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", 1)

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $iConnect
            $rKabina = GUICtrlRead($iKabina)
            $rType = GUICtrlRead($iType)
            $rModel = GUICtrlRead($iModel)
            $rSerialNum = GUICtrlRead($iSerialNum)
            $rInv = GUICtrlRead($iInv)

            Select
                Case (Not StringStripWS($rKabina, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Кабинет - пустое')
                Case (Not StringStripWS($rType, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Тип - пустое')
                Case (Not StringStripWS($rModel, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Модель - пустое')
                Case (Not StringStripWS($rSerialNum, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Серийный номер - пустое')
                Case (Not StringStripWS($rInv, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Инвентарник - пустое')
                Case $hFile = -1
                    MsgBox(4096, 'Ошибка', 'Невозможно открыть файл.')
                Case Else
                    _hide() ;отключает все элементы ввода и кнопку
                    $sInfo = '======================================================================================' & @CRLF & _
                                   '[МЕСТОПОЛОЖЕНИЕ:]' & @CRLF & _
                            @TAB & 'Дата: ................... ' & @MDAY & '.' & @MON & '.' & @YEAR & ' ' & @CRLF & _
                            @TAB & 'Кабинет: ................ ' & $rKabina & @CRLF & _
                            @TAB & 'Тип: .................... ' & $rType & @CRLF & _
                            @TAB & 'Модель: ................. ' & $rModel & @CRLF & _
                            @TAB & 'Серийный номер: ......... ' & $rSerialNum & @CRLF & _
                            @TAB & 'Инвентарный номер: ...... ' & $rInv & @CRLF & _
                            @TAB & 'Учетная запись: ......... ' & @UserName & @CRLF & @CRLF
                    $sInfo &= _InfoPC()
                    FileWrite($hFile, $sInfo)
                    FileClose($hFile)
                    _show() ;включает все элементы ввода и кнопку
                    _ShowOtchot()
            EndSelect
    EndSwitch
WEnd



Func _InfoPC()
    Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2')
    Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30)
    Local $ObjProcessor = $ObjService.ExecQuery('SELECT * FROM Win32_Processor', 'WQL', 0x30)
    Local $ObjMemory = $ObjService.ExecQuery('SELECT * FROM Win32_PhysicalMemory')
    Local $ObjNet = $ObjService.ExecQuery('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x30)
    Local $ObjGraph = $ObjService.ExecQuery('SELECT * FROM Win32_VideoController', 'WQL', 0x30)
    Local $ObjDrive = $ObjService.ExecQuery('SELECT * FROM Win32_DiskDrive', 'WQL', 0x30)
    Local $ObjCDDrive = $ObjService.ExecQuery('SELECT * FROM Win32_CDROMDrive', 'WQL', 0x30)
    Local $ObjRam = $ObjService.ExecQuery('SELECT * FROM Win32_ComputerSystem')
    Local $sNameComput = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0', 'szTargetName')
    Local $sProduct = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName')
    Local $sBuild = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ReleaseId')

    Local $sItemM, $sInfo = '[КОНФИГУРАЦИЯ:]' & @CRLF & @TAB & 'Имя компьютера: ......... ' & $sNameComput & @CRLF & _
            @TAB & 'Операционная система: ... ' & $sProduct & ' ' & $sBuild & ' ' & '(' & @OSArch & ')' & @CRLF

    If IsObj($ObjService) Then
        For $objItemP In $ObjProcessor
            $sInfo &= @TAB & 'Процессор: .............. ' & $objItemP.Name & @CRLF
        Next
        For $objItemMB In $ObjMB
            $sInfo &= @TAB & 'Материнская плата: ...... ' & $objItemMB.Product & @CRLF
        Next
        For $ObjItemM In $ObjMemory
            $sItemM = $objItemM.Speed
        Next
        For $objItemR In $ObjRam
            $sInfo &= @TAB & 'RAM: .................... ' & Round($objItemR.TotalPhysicalMemory / 1024 / 1024 ^ 2, 0) & ' GB | ' & $ObjMemory.Count & ' pieces | ' & $sItemM & ' Mhz' & @CRLF
        Next
        For $ObjItemG In $ObjGraph
            $sInfo &= @TAB & 'Видеокарта: ............. ' & $ObjItemG.Name & ' | RAM: ' & $ObjItemG.AdapterRAM / 1024 ^ 2 & ' Mb' & @CRLF
        Next
        For $ObjItemD In $ObjDrive
            $sInfo &= @TAB & 'Жесткие диск: ........... ' & $ObjItemD.Model & ' | Size: ' & Round($ObjItemD.Size / 1024 / 1024 / 1024) & ' Gb' & @CRLF
        Next
        For $ObjItemCD In $ObjCDDrive
            $sInfo &= @TAB & 'Дисковод: ............... ' & $ObjItemCD.Name & @CRLF
        Next
        For $ObjItemN In $ObjNet
            If $ObjItemN.PhysicalAdapter = True Then
                $sInfo &= @TAB & 'Сетевой адаптер: ........ ' & $ObjItemN.Name & @CRLF
            EndIf
        Next
    EndIf
    $sInfo &= @CRLF

    Return $sInfo
EndFunc   ;==>_InfoPC

Func _hide() ;функция. отключает элементы ввода и кнопку, пока работает скрипт
    GUICtrlSetState($iConnect, $GUI_disable)
    GUICtrlSetState($iKabina, $GUI_disable)
    GUICtrlSetState($iType, $GUI_disable)
    GUICtrlSetState($iModel, $GUI_disable)
    GUICtrlSetState($iSerialNum, $GUI_disable)
    GUICtrlSetState($iInv, $GUI_disable)
EndFunc   ;==>_hide

Func _show() ;функция. включает элементы ввода и кнопку, когда скрипт отработал
    GUICtrlSetState($iConnect, $GUI_enable)
    GUICtrlSetState($iKabina, $GUI_enable)
    GUICtrlSetState($iType, $GUI_enable)
    GUICtrlSetState($iModel, $GUI_enable)
    GUICtrlSetState($iSerialNum, $GUI_enable)
    GUICtrlSetState($iInv, $GUI_enable)
 EndFunc   ;==>_show

Opt("MustDeclareVars",1)

Func _a()
Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _
&"authenticationLevel=Pkt}!\\"& _
@ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _
('SELECT * FROM WmiMonitorID'), _
$lll,$sll,$sss="",$lsl,$lls,$i,$z
For $z In $lss
$lsl=$z.UserFriendlyName
For $i=0 To Ubound($lsl)-1
if ($lsl[$i]) Then $lll&=Chr($lsl[$i])
Next
$lls=$z.SerialNumberID
For $i=0 To Ubound($lls)-1
if ($lls[$i]) Then $sll&=Chr($lls[$i])
Next
$sss&="Model"&@TAB&@TAB&":   "&$lll&@CR&"Serial Number"&@TAB&":   "&$sll&@CR&@CR
$lll=""
$sll=""
Next

$lss=Null
$sls=Null
 $sInfo &= @CRLF
EndFunc

 Func _ShowOtchot()
    $Form1 = GUICreate("Отчёт", 482, 438, Default, Default, Default, 0x00000080, $Main)
    GUISetBkColor(0x02101B)
    $Edit1 = GUICtrlCreateEdit("", 0, 0, 482, 385)
    GUICtrlSetData(-1, FileRead($fFile))
    $CopyBtn = GUICtrlCreateButton("Копировать", 194, 400, 99, 25, $BS_DEFPUSHBUTTON)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Form1, '', $i) ;Прозрачность 0-255
Next
    GUISetState(@SW_SHOW)
    While 1
        $msg = GUIGetMsg()
        Switch $msg
            Case $CopyBtn
                ClipPut(GUICtrlRead($Edit1))
                DirCreate (@ScriptDir & "\COPY")
                FileCopy(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", @ScriptDir & "\COPY", 1)
                MsgBox(64, "Статус", 'Скопировано', Default, $Main)
            Case -3
                GUIDelete($Form1)
                WinActivate($Main)
                ExitLoop
        EndSwitch
    WEnd
EndFunc

Func Display_Info()
    Local $oComErr, $oWmi, $oInstances

    $oComErr = ObjEvent("AutoIt.Error", comm_error_handler)
    #forceref $oComErr

    ;Get WMI object
    $oWmi = ObjGet("winmgmts:\root\WMI")
    If Not IsObj($oWmi) Then Exit MsgBox($MB_ICONERROR, "ERROR", "Unable to create WMI object")

    ;Select object instances
    $oInstances = $oWmi.ExecQuery("SELECT * FROM WMIMonitorID")
    If $oInstances.Count = 0 Then Exit MsgBox($MB_ICONWARNING,"Warning","No objects found")
    
    ; Changed part
    Local $aReturn[2] ; change number if you want to return more info

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then $aReturn[0] = StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName))
            If IsArray(.SerialNumberId)   Then $aReturn[1] = StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId))
        EndWith
    Next
    
    Return $aReturn
    
EndFunc

Func convert_uint16_array_to_string($aBytes)
    Local $s  = ""

    For $i in $aBytes
        If $i <> 0 Then $s &= Chr($i)
    Next

    Return $s
EndFunc

Func comm_error_handler($oComError)
    ConsoleWrite(@CRLF)
    ConsoleWrite(StringFormat("Script Line  = %s", $oComError.ScriptLine) & @CRLF)
    ConsoleWrite(StringFormat("Win Err Desc = %s", StringStripWS($oComError.WinDescription, $STR_STRIPTRAILING)) & @CRLF)
    ConsoleWrite(StringFormat("Error Number = %i (0x%x)", $oComError.Number, $oComError.Number) & @CRLF)
    ConsoleWrite(StringFormat("Error Desc   = %s", $oComError.Description) & @CRLF)
    Exit
EndFunc

Oh.Not have error but not see  information about monitors(Need write in the last line)

Безымянный.jpg

Link to post
Share on other sites

Added this part to the end under "Configuration" 😛 , check if it works..

Local $aDisplayInfo = Display_Info()
        if not $aDisplayInfo = "" then
            $sInfo &= @TAB & 'UserFriendlyName: ........' & $aDisplayInfo[0] & @CRLF
            $sInfo &= @TAB & 'SerialNumberId: ........' & $aDisplayInfo[1] & @CRLF
        endif

Code:

#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <ButtonConstants.au3>

#include <Constants.au3>
#include <Array.au3>

#RequireAdmin
#NoTrayIcon

;Все что написано, посде ';' явлется комментарием и ни как не влияет на работу скрипта.

Global $iKabina, $iType, $iKabina, $iModel, $iSerialNum, $iInv ;объявляем переменные, которые будут использоваться в цикле
Global $rKabina, $rType, $rModel, $rSerialNum, $rInv, $Main, $iConnect, $hFile, $sInfo, $CopyBtn, $fFile = @ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt"

$Main = GUICreate('Инвентаризация', 315, 352) ;рисуем главное окно
GUISetBkColor(0x02101B)

$iKabina = GUICtrlCreateInput('', 20, 30, 272, 21)
$iType = GUICtrlCreateInput('', 20, 75, 272, 21)
$iModel = GUICtrlCreateInput('', 20, 120, 272, 21)
$iSerialNum = GUICtrlCreateInput('', 20, 165, 272, 21)
$iInv = GUICtrlCreateInput('', 20, 210, 272, 21)

GUISetFont(10, 800, 0, 'Tahoma'); Устанавливает шрифт по умолчанию для последующих элементов GUI-окна.
$iConnect = GUICtrlCreateButton('Передать', 23, 305, 267, 33, $BS_DEFPUSHBUTTON) ;создаем кнопку подключения

GUICtrlSetDefColor(0xDEDEDE); Устанавливает цвет текста по умолчанию для последующих элементов GUI-окна.
GUICtrlCreateLabel('Кабинет', 20, 10, 150, 17)
GUICtrlCreateLabel('Тип', 20, 55, 150, 17)
GUICtrlCreateLabel('Модель', 20, 100, 150, 17)
GUICtrlCreateLabel('Серийный номер', 20, 145, 150, 17)
GUICtrlCreateLabel('Инвентарник', 20, 190, 150, 17)

WinSetTrans($Main, '', 0)
GUISetState(@SW_SHOW)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Main, '', $i) ;Прозрачность 0-255
Next

$hFile = FileOpen(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", 1)

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $iConnect
            $rKabina = GUICtrlRead($iKabina)
            $rType = GUICtrlRead($iType)
            $rModel = GUICtrlRead($iModel)
            $rSerialNum = GUICtrlRead($iSerialNum)
            $rInv = GUICtrlRead($iInv)

            Select
                Case (Not StringStripWS($rKabina, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Кабинет - пустое')
                Case (Not StringStripWS($rType, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Тип - пустое')
                Case (Not StringStripWS($rModel, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Модель - пустое')
                Case (Not StringStripWS($rSerialNum, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Серийный номер - пустое')
                Case (Not StringStripWS($rInv, 8))
                    MsgBox(16 + 8192 + 262144, 'Error', 'Поле Инвентарник - пустое')
                Case $hFile = -1
                    MsgBox(4096, 'Ошибка', 'Невозможно открыть файл.')
                Case Else
                    _hide() ;отключает все элементы ввода и кнопку
                    $sInfo = '======================================================================================' & @CRLF & _
                                   '[МЕСТОПОЛОЖЕНИЕ:]' & @CRLF & _
                            @TAB & 'Дата: ................... ' & @MDAY & '.' & @MON & '.' & @YEAR & ' ' & @CRLF & _
                            @TAB & 'Кабинет: ................ ' & $rKabina & @CRLF & _
                            @TAB & 'Тип: .................... ' & $rType & @CRLF & _
                            @TAB & 'Модель: ................. ' & $rModel & @CRLF & _
                            @TAB & 'Серийный номер: ......... ' & $rSerialNum & @CRLF & _
                            @TAB & 'Инвентарный номер: ...... ' & $rInv & @CRLF & _
                            @TAB & 'Учетная запись: ......... ' & @UserName & @CRLF & @CRLF
                    $sInfo &= _InfoPC()
                    FileWrite($hFile, $sInfo)
                    FileClose($hFile)
                    _show() ;включает все элементы ввода и кнопку
                    _ShowOtchot()
            EndSelect
    EndSwitch
WEnd



Func _InfoPC()
    Local $ObjService = ObjGet('winmgmts:{impersonationLevel = impersonate}!\\' & @ComputerName & '\root\cimv2')
    Local $ObjMB = $ObjService.ExecQuery('SELECT * FROM Win32_BaseBoard', 'WQL', 0x30)
    Local $ObjProcessor = $ObjService.ExecQuery('SELECT * FROM Win32_Processor', 'WQL', 0x30)
    Local $ObjMemory = $ObjService.ExecQuery('SELECT * FROM Win32_PhysicalMemory')
    Local $ObjNet = $ObjService.ExecQuery('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x30)
    Local $ObjGraph = $ObjService.ExecQuery('SELECT * FROM Win32_VideoController', 'WQL', 0x30)
    Local $ObjDrive = $ObjService.ExecQuery('SELECT * FROM Win32_DiskDrive', 'WQL', 0x30)
    Local $ObjCDDrive = $ObjService.ExecQuery('SELECT * FROM Win32_CDROMDrive', 'WQL', 0x30)
    Local $ObjRam = $ObjService.ExecQuery('SELECT * FROM Win32_ComputerSystem')
    Local $sNameComput = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\DataStore\Machine\0', 'szTargetName')
    Local $sProduct = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName')
    Local $sBuild = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ReleaseId')

    Local $sItemM, $sInfo = '[КОНФИГУРАЦИЯ:]' & @CRLF & @TAB & 'Имя компьютера: ......... ' & $sNameComput & @CRLF & _
            @TAB & 'Операционная система: ... ' & $sProduct & ' ' & $sBuild & ' ' & '(' & @OSArch & ')' & @CRLF

    If IsObj($ObjService) Then
        For $objItemP In $ObjProcessor
            $sInfo &= @TAB & 'Процессор: .............. ' & $objItemP.Name & @CRLF
        Next
        For $objItemMB In $ObjMB
            $sInfo &= @TAB & 'Материнская плата: ...... ' & $objItemMB.Product & @CRLF
        Next
        For $ObjItemM In $ObjMemory
            $sItemM = $objItemM.Speed
        Next
        For $objItemR In $ObjRam
            $sInfo &= @TAB & 'RAM: .................... ' & Round($objItemR.TotalPhysicalMemory / 1024 / 1024 ^ 2, 0) & ' GB | ' & $ObjMemory.Count & ' pieces | ' & $sItemM & ' Mhz' & @CRLF
        Next
        For $ObjItemG In $ObjGraph
            $sInfo &= @TAB & 'Видеокарта: ............. ' & $ObjItemG.Name & ' | RAM: ' & $ObjItemG.AdapterRAM / 1024 ^ 2 & ' Mb' & @CRLF
        Next
        For $ObjItemD In $ObjDrive
            $sInfo &= @TAB & 'Жесткие диск: ........... ' & $ObjItemD.Model & ' | Size: ' & Round($ObjItemD.Size / 1024 / 1024 / 1024) & ' Gb' & @CRLF
        Next
        For $ObjItemCD In $ObjCDDrive
            $sInfo &= @TAB & 'Дисковод: ............... ' & $ObjItemCD.Name & @CRLF
        Next
        For $ObjItemN In $ObjNet
            If $ObjItemN.PhysicalAdapter = True Then
                $sInfo &= @TAB & 'Сетевой адаптер: ........ ' & $ObjItemN.Name & @CRLF
            EndIf
        Next
        
        Local $aDisplayInfo = Display_Info()
        if not $aDisplayInfo = "" then
            $sInfo &= @TAB & 'UserFriendlyName: ........' & $aDisplayInfo[0] & @CRLF
            $sInfo &= @TAB & 'SerialNumberId: ........' & $aDisplayInfo[1] & @CRLF
        endif
        
    EndIf
    $sInfo &= @CRLF

    Return $sInfo
EndFunc   ;==>_InfoPC

Func _hide() ;функция. отключает элементы ввода и кнопку, пока работает скрипт
    GUICtrlSetState($iConnect, $GUI_disable)
    GUICtrlSetState($iKabina, $GUI_disable)
    GUICtrlSetState($iType, $GUI_disable)
    GUICtrlSetState($iModel, $GUI_disable)
    GUICtrlSetState($iSerialNum, $GUI_disable)
    GUICtrlSetState($iInv, $GUI_disable)
EndFunc   ;==>_hide

Func _show() ;функция. включает элементы ввода и кнопку, когда скрипт отработал
    GUICtrlSetState($iConnect, $GUI_enable)
    GUICtrlSetState($iKabina, $GUI_enable)
    GUICtrlSetState($iType, $GUI_enable)
    GUICtrlSetState($iModel, $GUI_enable)
    GUICtrlSetState($iSerialNum, $GUI_enable)
    GUICtrlSetState($iInv, $GUI_enable)
 EndFunc   ;==>_show

Opt("MustDeclareVars",1)

Func _a()
Local $sls=ObjGet("winmgmts:{impersonationLevel=impersonate," _
&"authenticationLevel=Pkt}!\\"& _
@ComputerName&'\root\wmi'),$lss=$sls.ExecQuery _
('SELECT * FROM WmiMonitorID'), _
$lll,$sll,$sss="",$lsl,$lls,$i,$z
For $z In $lss
$lsl=$z.UserFriendlyName
For $i=0 To Ubound($lsl)-1
if ($lsl[$i]) Then $lll&=Chr($lsl[$i])
Next
$lls=$z.SerialNumberID
For $i=0 To Ubound($lls)-1
if ($lls[$i]) Then $sll&=Chr($lls[$i])
Next
$sss&="Model"&@TAB&@TAB&":   "&$lll&@CR&"Serial Number"&@TAB&":   "&$sll&@CR&@CR
$lll=""
$sll=""
Next

$lss=Null
$sls=Null
 $sInfo &= @CRLF
EndFunc

 Func _ShowOtchot()
    $Form1 = GUICreate("Отчёт", 482, 438, Default, Default, Default, 0x00000080, $Main)
    GUISetBkColor(0x02101B)
    $Edit1 = GUICtrlCreateEdit("", 0, 0, 482, 385)
    GUICtrlSetData(-1, FileRead($fFile))
    $CopyBtn = GUICtrlCreateButton("Копировать", 194, 400, 99, 25, $BS_DEFPUSHBUTTON)

For $i = 0 To 230 Step 9
    Sleep(10)
    WinSetTrans($Form1, '', $i) ;Прозрачность 0-255
Next
    GUISetState(@SW_SHOW)
    While 1
        $msg = GUIGetMsg()
        Switch $msg
            Case $CopyBtn
                ClipPut(GUICtrlRead($Edit1))
                DirCreate (@ScriptDir & "\COPY")
                FileCopy(@ScriptDir & "\" & "(" & @MDAY & "." & @MON & "." & @YEAR & ")" & ".txt", @ScriptDir & "\COPY", 1)
                MsgBox(64, "Статус", 'Скопировано', Default, $Main)
            Case -3
                GUIDelete($Form1)
                WinActivate($Main)
                ExitLoop
        EndSwitch
    WEnd
EndFunc

Func Display_Info()
    Local $oComErr, $oWmi, $oInstances

    $oComErr = ObjEvent("AutoIt.Error", comm_error_handler)
    #forceref $oComErr

    ;Get WMI object
    $oWmi = ObjGet("winmgmts:\root\WMI")
    If Not IsObj($oWmi) Then Exit MsgBox($MB_ICONERROR, "ERROR", "Unable to create WMI object")

    ;Select object instances
    $oInstances = $oWmi.ExecQuery("SELECT * FROM WMIMonitorID")
    If $oInstances.Count = 0 Then Exit MsgBox($MB_ICONWARNING,"Warning","No objects found")
    
    ; Changed part
    Local $aReturn[2] ; change number if you want to return more info

    ;Display instance properties
    For $oInstance in $oInstances
        With $oInstance
            ConsoleWrite(@CRLF)
            If IsArray(.UserFriendlyName) Then $aReturn[0] = StringFormat("UserFriendlyName       = %s", convert_uint16_array_to_string(.UserFriendlyName))
            If IsArray(.SerialNumberId)   Then $aReturn[1] = StringFormat("SerialNumberId         = %s", convert_uint16_array_to_string(.SerialNumberId))
        EndWith
    Next
    
    Return $aReturn
    
EndFunc

Func convert_uint16_array_to_string($aBytes)
    Local $s  = ""

    For $i in $aBytes
        If $i <> 0 Then $s &= Chr($i)
    Next

    Return $s
EndFunc

Func comm_error_handler($oComError)
    ConsoleWrite(@CRLF)
    ConsoleWrite(StringFormat("Script Line  = %s", $oComError.ScriptLine) & @CRLF)
    ConsoleWrite(StringFormat("Win Err Desc = %s", StringStripWS($oComError.WinDescription, $STR_STRIPTRAILING)) & @CRLF)
    ConsoleWrite(StringFormat("Error Number = %i (0x%x)", $oComError.Number, $oComError.Number) & @CRLF)
    ConsoleWrite(StringFormat("Error Desc   = %s", $oComError.Description) & @CRLF)
    Exit
EndFunc
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By DJ143
      I have a autoit exe file which is used in upload/browse file functionality.  This has been integrated with selenium framework and I am invoking the autoit exe using Java process and runtime. 
      Now the issue is when I run the scripts and invoke the autoit exe in local it works perfectly.  But when I use selenium grid or jenkins to run the scripts in another windows server it is not working.
      Can anyone please suggest any solution for this?
    • By hek
      Hey everyone,
      Was wondering how I would be able to implement this on a local computer instead of using connectserver? 
      Any suggestions or help would be appreciated. Thanks. 
    • By Hermes
      Hello, the script below will read column A from an excel file - and if a value matches in the browser, it will click the corresponding link and click on a specific button to paste the data, then writes "Completed" in Column B. It will continue to read from the excel file and do the same thing for all the remaining rows.
      #Include "Chrome.au3" #Include "wd_core.au3" #Include "wd_helper.au3" #Include "WinHttp.au3" #include <MsgBoxConstants.au3> #include <File.au3> #include <IE.au3> #include <Array.au3> #include <INet.au3> #include <AutoItConstants.au3> #include <WinAPIFiles.au3> #include <GDIPlus.au3> #include <Excel.au3> #Include "WinHttp.au3" #Include "_HtmlTable2Array.au3" Local $sDesiredCapabilities, $sSession SetupChrome() _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) _WD_LoadWait($sSession) _WD_Navigate($sSession, "table1.html") _WD_LoadWait($sSession) _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, "//table[@class='main']") Local $sElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, "//table[@class='main']") ;ConsoleWrite ("mat-table " & $sElement & @CRLF) Local $aArray1 = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, ".//td[contains(@class,'data')]", $sElement, True) sleep(1000) For $i = 0 to UBound($aArray1) - 1 $aArray1[$i] = _WD_ElementAction($sSession, $aArray1[$i], 'text') Next ;_ArrayDisplay($aArray1) ;Email variables $SmtpServer = "" ; address for the smtp-server to use - REQUIRED $FromName = "Hermes" ; name from who the email was sent $FromAddress = "sender@gmail.com" ; address from where the mail should come $ToAddress = "recipient@gmail.com" ; destination address of the email - REQUIRED, use commas (,) to add more email addresses $Subject = "File not found" ; subject from the email - can be anything you want it to be $Body = "File not found!" ; the messagebody from the mail - can be left blank but then you get a blank mail $AttachFiles = "" ; the file(s) you want to attach seperated with a ; (Semicolon) - leave blank if not needed $CcAddress = "" ; address for cc - leave blank if not needed $BccAddress = "" ; address for bcc - leave blank if not needed $Importance = "High" ; Send message priority: "High", "Normal", "Low" $Username = "" ; username for the account used from where the mail gets sent - REQUIRED $Password = "" ; password for the account used from where the mail gets sent - REQUIRED $IPPort = 25 ; port used for sending the mail $ssl = 0 ; enables/disables secure socket layer sending - put to 1 if using httpS $tls = 0 ; enables/disables TLS when required Local $oAppl = _Excel_Open() Local $sWorkbook = "c:\test.xlsx" Local $oWorkbook = _Excel_BookOpen($oAppl, $sWorkbook) ;open excel and pass both parameters If FileExists($sWorkbook) Then ;Check if the file exist. Local $oAppl = _Excel_Open() Local $sWorkbook = "c:\test.xlsx" Local $oWorkbook = _Excel_BookOpen($oAppl, $sWorkbook) ;open excel and pass both parameters Local $aArray2 = _Excel_RangeRead($oWorkbook,Default,$oWorkbook.ActiveSheet.Usedrange.Columns("A:A")) Local $iIdx Local $Skipline = 0 ;0==> first line Do Local $temprf For $i = 0 To UBound($aArray2) - 1 $temprf &= $aArray2[$i] _WD_WaitElement($sSession, $_WD_LOCATOR_ByXPath, ".//a[contains(@class,'edit') and contains(text(),'Edit')]") Local $aElement = _WD_FindElement($sSession, $_WD_LOCATOR_ByXPath, ".//a[contains(@class,'edit') and contains(text(),'Edit')]", $sElement, True) $iIdx = _ArraySearch($aArray1, $aArray2[$i]) If @error Then ContinueLoop _WD_ElementAction($sSession, $aElement[$iIdx], 'click') If $i < $Skipline Then ContinueLoop $oRange = $oWorkbook.ActiveSheet.Range("B" & $i + 1 & ":XFD" & $i + 1) _Excel_RangeCopyPaste($oWorkbook.Activesheet, $oRange) ;Paste Local $oTest4 = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "pastebutton") _WD_ElementAction($sSession, $oTest4, 'click') Sleep(1000) ;Save Button Local $save3 = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "button.button") _WD_ElementAction($sSession, $save3, 'click') _Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, "Completed", "B" & $i+1) sleep(1000) Next Until (Not @error) _Excel_Close($oWorkbook) Else _INetSmtpMailCom($SmtpServer, $FromName, $FromAddress, $ToAddress, $Subject, $Body, $CcAddress, $BccAddress, $Importance, $Username, $Password, $IPPort, $ssl, $tls) Exit EndIf _WD_LoadWait($sSession) ;Attaching files to emails Func _INetSmtpMailCom($s_SmtpServer, $s_FromName, $s_FromAddress, $s_ToAddress, $s_Subject = "", $as_Body = "", $s_CcAddress = "", $s_BccAddress = "", $s_Importance="Normal", $s_Username = "", $s_Password = "", $IPPort = 25, $ssl = 0, $tls = 0) Local $objEmail = ObjCreate("CDO.Message") $objEmail.From = '"' & $s_FromName & '" <' & $s_FromAddress & '>' $objEmail.To = $s_ToAddress Local $i_Error = 0 Local $i_Error_desciption = "" If $s_CcAddress <> "" Then $objEmail.Cc = $s_CcAddress If $s_BccAddress <> "" Then $objEmail.Bcc = $s_BccAddress $objEmail.Subject = $s_Subject If StringInStr($as_Body, "<") And StringInStr($as_Body, ">") Then $objEmail.HTMLBody = $as_Body Else $objEmail.Textbody = $as_Body & @CRLF EndIf $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = $s_SmtpServer If Number($IPPort) = 0 then $IPPort = 25 $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = $IPPort ;Authenticated SMTP If $s_Username <> "" Then $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = $s_Username $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = $s_Password EndIf ; Set security params If $ssl Then $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True If $tls Then $objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendtls") = True ;Update settings $objEmail.Configuration.Fields.Update ; Set Email Importance Switch $s_Importance Case "High" $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "High" Case "Normal" $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Normal" Case "Low" $objEmail.Fields.Item ("urn:schemas:mailheader:Importance") = "Low" EndSwitch $objEmail.Fields.Update ; Sent the Message $objEmail.Send $objEmail="" EndFunc ;==>_INetSmtpMailCom Local $aDir = _FileListToArrayRec(@TempDir, "scoped_dir*;chrome_*", $FLTAR_FOLDERS, $FLTAR_NORECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH) Sleep(2000) For $i = 1 To $aDir[0] DirRemove($aDir[$i], $DIR_REMOVE) Next _WD_LoadWait($sSession) _WD_Shutdown() Func SetupChrome() _WD_Option('Driver', 'chromedriver.exe') _WD_Option('Port', 9515) _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"') $sDesiredCapabilities = '{"capabilities": {"alwaysMatch": {"goog:chromeOptions": {"w3c": true, "args":["start-maximized","disable-infobars"]}}}}' EndFunc ;==>SetupChrome If the excel file doesn't exists in the folder, it will send an email to a specific recipient.
      What i am trying figure out now is if the excel crashes while the script/loop is running, I want to relaunch the excel file continue to the last row before the excel crashed. So if the value of column B is not marked as "completed", it should continue from that row
      Appreciate any help that I can get to achieve this.
      table1.html test.xlsx
    • By adityaparakh
      Hello ,
      I am trying to use Websockets in AutoIt.
      It is to fetch live stock market prices , API is provided and documentation available for python language.
      The link for the code snippet is :
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Introduction
      https://symphonyfintech.com/xts-market-data-front-end-api-v2/#tag/Instruments/paths/~1instruments~1subscription/post
       
      https://github.com/symphonyfintech/xts-pythonclient-api-sdk
       
      Second Link is to subscribe to a list of ExchangeInstruments.
      Now I would like to get live stock ltp (LastTradedPrice) for a few stocks whose "ExchangeInstrumentID" I know.
      I am able to use the WinHttp object to perform actions using simple codes like below :
      I have the secretKey and appkey and can generate the needed token. And get the unique ExchangeInstrumentID.

      Below code is just for example of how I am using WinHttp. Unrelated to socket part.
      Global $InteractiveAPItoken = IniRead(@ScriptDir & "\Config.ini", "token", "InteractiveAPItoken", "NA") $baseurl = "https://brokerlink.com/interactive/" $functionurl = "orders" $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("POST", $baseurl & $functionurl, False) $oHTTP.SetRequestHeader("Content-Type", "application/json;charset=UTF-8") $oHTTP.SetRequestHeader("authorization", $InteractiveAPItoken) $pD = '{ "exchangeSegment": "NSEFO", "exchangeInstrumentID": ' & $exchangeInstrumentID & ', "productType": "' & $producttype & '", "orderType": "MARKET", "orderSide": "' & $orderside & '", "timeInForce": "DAY", "disclosedQuantity": 0, "orderQuantity": ' & $qty & ', "limitPrice": 0, "stopPrice": 0, "orderUniqueIdentifier": "' & $orderidentifier & '"}' $oHTTP.Send($pD) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status
          
          
      But am struggling to understand and use socket.
      Would be of great help if you can have a look at the link mentioned above and help with the code sample for AutoIt.
      To connect and listen to a socket.
      Thanks a lot
       
    • By Hermes
      Hi, I have a site that has the following elements below: 
      <div>More element here</div> <div>More element here</div> <div>More element here</div> When I do this in Auto It:
      Local $oSelectDiv = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "div") _WD_HighlightElement($sSession, $oSelectDiv, 1) I also tried to add [3], but it doesnt seems to work:
      Local $oSelectDiv = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "div[3]") _WD_HighlightElement($sSession, $oSelectDiv, 1) It always highlight the first one, but I am trying to highlight the 3rd in the list. Is there anyway to select the 3rd div without having to add any class/id in the divs, and without using XPATH? The structure of the elements in that site were built that way.
×
×
  • Create New...