Jump to content

Uber easy question for you GOD's OF SCRIPTING


 Share

Recommended Posts

I want to run a dos command and get the data:

This example shows what I know (witch is not much) with autoIT.

Run(@ComSpec & " /c ipconfig /all >c:\test\test2.txt","",@SW_HIDE)
Sleep(800)
Run(@ComSpec & " /c wmic csproduct get name > c:\test\test3.txt","",@SW_HIDE)

Now what i want to do is NOT write the TXT file but to a CSV file. More or less I want to get the Ip and MAC address that is in the first command and place them on a row. THEN I want the second command to write out the last entry on the SAME row. (i.e. 192.168.1.1,00.00.00.00.00,serialNUM) THEN I want to append(witch I already know).

My question is:

How to take the information generated and chop it up and write what I need and discard the rest.

Many thanks!

Link to comment
Share on other sites

StdoutRead(...)
StringRegExp(...)

hint: StderrRead shows better example how to use StdoutRead

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

also stdout may help

#include <AutoItConstants.au3>

$sCommands = "ipconfig /all"

$iPID = Run(@ComSpec & " /c " & $sCommands, "", @SW_HIDE , $stdout_child)

$sOutput = ""

 While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
 WEnd

 msgbox(0, '' , $sOutput)

 

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

You can use also WMI to enumarate the needed information. Search for: WMI cimv2 Win32_NetworkAdapterConfiguration ExecQuery

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

Thanks

 

I used the examples and came up with this. 

I changes the FileWriteLine to FileWrite thinking I was not getting the proper output to propagate the file. (still does not put the data in the file, But does make the file)

If I want to do a WriteLine how can I go into the information generated and find the line that I want and write only that line? In Dos we can do a findstr to do this. 

 

Thanks UEZ.. heck you like a celebrity here! Not to play down the excellent posters IamTheKy and mliPok.I was expecting to take this into WIM once I understood how to do a basic Ipconfig. I attempt to craw before I walk! Helps with the medical bills :)

 

example3.au3

Link to comment
Share on other sites

  • Moderators

Look at FileRead, or FileReadToArray. You can use these to parse through the file, find the text you want, and extract it.

"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 comment
Share on other sites

Hi again Logan! You gave me awsome advise on another topic!

The script a offered does to read from a file so i am not sure how to do a "Filereadtoarray" I assume I need a file first. Are you suggestion that I do the "ipconfig /all > c:\test.txt" and then read c:\test.txt an array? That I can see, but can I not grab the info that is returned? Seems inefficient to write a file to read that file then to write to another file. ( Moles and trolls, moles and trolls, work, work, work, work, work. We never see the light of day.) 

 

Thanks

Link to comment
Share on other sites

  • Moderators

Based on the code UEZ provided you, a typical value for a single $sOutput would be:

Windows IP Configuration

   Host Name . . . . . . . . . . . . : Machine1
   Primary Dns Suffix  . . . . . . . : mydomain.com
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : mydomain.com

Ethernet adapter Local Area Connection:

   Connection-specific DNS Suffix  . : mydomain.com
   Description . . . . . . . . . . . : Intel(R) PRO/1000 MT Network Connection
   Physical Address. . . . . . . . . : 00-50-56-A3-5C-8E
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::d827:b04e:879d:7652%11(Preferred) 
   IPv4 Address. . . . . . . . . . . : 10.10.2.23(Preferred)

You are going to have to parse it in some way, either writing out to a temp file or using StringInStr, a Regex, etc. Can you be more specific on what text exactly you want to extract?

"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 comment
Share on other sites

ewww "parse".. 

here is the DOS bat file that I am trying to get into AutoIT. I think AutoIT is the cleaner and more efficient way to accomplish what i want.

 

If I go with piping it to a file then I can use the AutoIT findstring.. that seems to be the best practice.

I feel if I can get over this simple "how to use the text I generate" AND "how to cut the text up" I can get to my goal.

gatherv002.bat

Link to comment
Share on other sites

#include <AutoItConstants.au3>
#include<array.au3>

$sCommands = "ipconfig /all"

$iPID = Run(@ComSpec & " /c " & $sCommands, "", @SW_HIDE , $stdout_child)

$sOutput = ""

 While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
 WEnd

 msgbox(0, '' , $sOutput)
 $aOutput = stringsplit($sOutput , @CR , 2)
 _ArrayDisplay($aOutput)

 

and then filewrite just the elements you want from the array? something like

for $i = 0 to ubound($aOutput) - 1

    If stringinstr($aOutput[$i] , "target string") Then Filewrite($destinationfile , $aOutput[$i])

next

 

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Here a part of your project with WMI:

Global Const $oErrorHandler = ObjEvent("AutoIt.Error", "ObjErrorHandler")

Global Const $sDelim = ",", $sCSVHeader = "Adapter" & $sDelim & "MAC" & $sDelim & "IP" & $sDelim & "Subnet" & $sDelim & "Gateway" & $sDelim & "Free space on C (GB)" & @CRLF
Global $sFCDriveFreeSpace = WMI_GetCDriveFreeSpace()
Global $aNetInfo = WMI_GetInfoFromActiveNetworkCard(), $sCSV, $i
If IsArray($aNetInfo) Then
    For $i = 0 To UBound($aNetInfo) - 1 Step 5
        $sCSV &= $aNetInfo[$i] & $sDelim & $aNetInfo[$i + 1] & $sDelim & $aNetInfo[$i + 2] & $sDelim & $aNetInfo[$i + 3] & $sDelim & $aNetInfo[$i + 4] & $sDelim & $sFCDriveFreeSpace & @CRLF
    Next
    ConsoleWrite($sCSVHeader & $sCSV & @CRLF)
    MsgBox(0, "Test", $sCSVHeader & $sCSV)
EndIf

Func WMI_GetInfoFromActiveNetworkCard($sHost = @ComputerName, $sUserID = "", $sPWD = "") ;coded by UEZ
    Local $objWMILocator = ObjCreate("WbemScripting.SWbemLocator")
    If @error Then Return SetError(1, 0, 0)
    Local $objWMIService = $objWMILocator.ConnectServer($sHost, "\root\cimv2", $sUserID, $sPWD, "", "", 0x80)
    If @error Then Return SetError(2, 0, 0)
    Local $iInterfaceIndex, $objItem, $colItems2, $objItem2
    Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_IP4RouteTable WHERE Destination='0.0.0.0'", "WQL", 0x30)
    If IsObj($colItems) Then
        Local $aActiveNetworkAdapter[25], $iCounter = 0
        For $objItem in $colItems
            $colItems2 = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE InterfaceIndex = " & $objItem.InterfaceIndex, "WQL", 0x30)
            For $objItem2 in $colItems2
                $aActiveNetworkAdapter[$iCounter] = $objItem2.Description
                $aActiveNetworkAdapter[$iCounter + 1] = $objItem2.MACAddress
                If IsArray($objItem2.IPAddress) Then $aActiveNetworkAdapter[$iCounter + 2] = $objItem2.IPAddress[0]
                If IsArray($objItem2.IPSubnet) Then $aActiveNetworkAdapter[$iCounter + 3] = $objItem2.IPSubnet[0]
                If IsArray($objItem2.DefaultIPGateway) Then $aActiveNetworkAdapter[$iCounter + 4] = $objItem2.DefaultIPGateway[0]
            Next
            $iCounter += 5
        Next
        ReDim $aActiveNetworkAdapter[$iCounter]
        Return $aActiveNetworkAdapter
    EndIf
    Return SetError(3, 0, 0)
EndFunc

Func WMI_GetInfoFromActiveNetworkCard2($sHost = @ComputerName)
    Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $sHost & "\root\cimv2")
    If @error Then Return SetError(1, 0, 0)
    Local $iInterfaceIndex, $objItem, $colItems2, $objItem2
    Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_IP4RouteTable WHERE Destination='0.0.0.0'", "WQL", 0x30)
    If IsObj($colItems) Then
        Local $aActiveNetworkAdapter[5]
        For $objItem in $colItems
            $colItems2 = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE InterfaceIndex = " & $objItem.InterfaceIndex, "WQL", 0x30)
            For $objItem2 in $colItems2
                $aActiveNetworkAdapter[0] = $objItem2.Description
                $aActiveNetworkAdapter[1] = $objItem2.MACAddress
                $aActiveNetworkAdapter[2] = $objItem2.IPAddress[0]
                $aActiveNetworkAdapter[3] = $objItem2.IPSubnet[0]
                $aActiveNetworkAdapter[4] = $objItem2.DefaultIPGateway[0]
                Return $aActiveNetworkAdapter
            Next
        Next
    Else
        Return SetError(2, 0, 0)
    EndIf
EndFunc

Func WMI_GetCDriveFreeSpace($sHost = @ComputerName, $sUserID = "", $sPWD = "")
    Local $objWMILocator = ObjCreate("WbemScripting.SWbemLocator")
    If @error Then Return SetError(1, 0, 0)
    Local $objWMIService = $objWMILocator.ConnectServer($sHost, "\root\cimv2", $sUserID, $sPWD, "", "", 0x80)
    If @error Then Return SetError(2, 0, 0)
    Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk WHERE Name = 'C:'", "WQL", 0x30), $objItem
    If IsObj($colItems) Then
        For $objItem in $colItems
            Return Round($objItem.FreeMegabytes / 1024, 2)
        Next
    Else
        Return SetError(2, 0, 0)
    EndIf
EndFunc

Func WMI_GetCDriveFreeSpace2($sHost = @ComputerName)
    Local $objWMIService = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $sHost & "\root\cimv2")
    If @error Then Return SetError(1, 0, 0)
    Local $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfDisk_LogicalDisk WHERE Name = 'C:'", "WQL", 0x30), $objItem
    If IsObj($colItems) Then
        For $objItem in $colItems
            Return Round($objItem.FreeMegabytes / 1024, 2)
        Next
    Else
        Return SetError(2, 0, 0)
    EndIf
EndFunc

Func ObjErrorHandler()
    ConsoleWrite(   "A COM Error has occured!" & @CRLF  & @CRLF & _
                                "err.description is: "    & @TAB & $oErrorHandler.description    & @CRLF & _
                                "err.windescription:"     & @TAB & $oErrorHandler & @CRLF & _
                                "err.number is: "         & @TAB & Hex($oErrorHandler.number, 8)  & @CRLF & _
                                "err.lastdllerror is: "   & @TAB & $oErrorHandler.lastdllerror   & @CRLF & _
                                "err.scriptline is: "     & @TAB & $oErrorHandler.scriptline     & @CRLF & _
                                "err.source is: "         & @TAB & $oErrorHandler.source         & @CRLF & _
                                "err.helpfile is: "       & @TAB & $oErrorHandler.helpfile       & @CRLF & _
                                "err.helpcontext is: "    & @TAB & $oErrorHandler.helpcontext & @CRLF _
                            )
EndFunc

 

The rest is homework for you. ;)

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...