Jump to content

Search for specifc text on a string.


MaGRauN
 Share

Go to solution Solved by Melba23,

Recommended Posts

Hello for everyone.

O make this script to search and return for a scpecifc text on a specific line on a SCCM 2007 smsts.log file.

#include <file.au3>
$LogX = "X:\Windows\temp\SMSTSLog\smsts.log"
$AbreLogX = FileOpen($LogX,0)
if $AbreLogX = 1 Then
    $ContaLinhas = _FileCountLines($LogX)
    for $l = 1 To $ContaLinhas
        $BuscaLinha = StringLeft((FileReadLine($LogX,$l)),26)
        if $BuscaLinha = "<![LOG[Client GUID = GUID:" Then
            $StateKnow = StringRegExp((FileReadLine($LogX,$l)),"State = Known")
            if $StateKnow = 1 Then
                $NomeDuplicado = StringLeft(StringTrimLeft((FileReadLine($LogX,$l)),79),(StringInStr(StringTrimLeft((FileReadLine($LogX,$l)),79),", State = Known")-1))
                GUISetState(@SW_HIDE)
                MsgBox(48,"Duplicidade identificada!","Equipamento com UUID duplicado : $NomeDuplicado")
                Exit
            EndIf
        EndIf
    Next
EndIf

One way to identify who line have a text when i find is the 26 first characters "<! [LOG [Client GUID = GUID:" string, and get the hostname.
This line has the string must identify: HOSTNAMEX

<![LOG[Client GUID = GUID:5B526601-B897-4A58-B27B-6509B7270417, Netbios name = HOSTAMEX, State = Known]LOG]!><time="11:08:05.679+180" date="09-18-2013" component="TSMBootstrap" context="" type="0" thread="1392" file="tspolicy.cpp:608">

Theres any whay to make this more faster or optimized?

Link to comment
Share on other sites

  • Moderators

MaGRauN,

A RegEx will extract that easily:

#include <Constants.au3>

; Get the line from the file
$sLine = '![LOG[Client GUID = GUID:5B526601-B897-4A58-B27B-6509B7270417, Netbios name = HOSTAMEX, State = Known]LOG]!><time="11:08:05.679+180" date="09-18-2013" component="TSMBootstrap" context="" type="0" thread="1392" file="tspolicy.cpp:608">'

; And then extract the bit you want
$aRet = StringRegExp($sLine, "(?i)Netbios name\s=\s(.*),", 3)

; And display it
MsgBox($MB_SYSTEMMODAL, "Extracted Data", $aRet[0])
SRE decode:

(?i}              - Case insensitive
Netbios name\s=\s - Look for this text (\s = space)
(.*)              - Capture everything until...
,                 - ...the next comma

3                 - This flag gives you an a array of all matches = even thought there should only be the one
All clear? :)

M23

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

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Hi Melba23. Thanks for response.

I change the code, using your help

$LogX = "e:\_dev\smsts.log";
$AbreLogX = FileOpen($LogX,0)
if $AbreLogX = 1 Then
    $ContaLinhas = _FileCountLines($LogX)
    for $l = 1 To $ContaLinhas
        $BuscaLinha = StringLeft((FileReadLine($LogX,$l)),26)
        if $BuscaLinha = "<![LOG[Client GUID = GUID:" Then
            $StateKnow = StringRegExp((FileReadLine($LogX,$l)),"State = Known")
            if $StateKnow = 1 Then
                ;$NomeDuplicado = StringLeft(StringTrimLeft((FileReadLine($LogX,$l)),79),(StringInStr(StringTrimLeft((FileReadLine($LogX,$l)),79),", State = Known")-1))
                $NomeDuplicado=StringRegExp(FileReadLine($LogX,$l),"(?i)Netbios name\s=\s(.*),", 3)
                MsgBox(48,"Duplicidade identificada!","Equipamento com UUID duplicado & $NomeDuplicado[0]")
                Exit
            EndIf
        EndIf
    Next
EndIf

You example substs all String... functions when i use to find text. Thanks again.

Another thing.

I use two parameters to determine the line when i need to identify the hostname: the 26 first characters, when i talk before, and the expression "State = Known", because have 2 more others possibilities, but i need to identify only on Possibility 2.

Note the GUID its unique for computer.

Possibility 1: <![LOG[Client GUID = GUID:5B526601-BUH7-4A58-B45B-6509B7270418, Netbios name = Unknown, State = Unknown]LOG]!>
Possibility 2: <![LOG[Client GUID = GUID:5B526601-BUH7-4A58-B45B-6509B7270417, Netbios name = HOSTNAMEX, State = Known]LOG]!>
Possibility 3: <![LOG[Client GUID = , Netbios name = , State = Known]LOG]!>

Have another way, more faster/optimized, to identify this specific line?

Edited by MaGRauN
Link to comment
Share on other sites

  • Moderators

MaGRauN,

The simplest way would be to check the return from the function like this:

$NomeDuplicado = StringRegExp(FileReadLine($LogX, $l), "(?i)Netbios name\s=\s(.*)," , 3)
Switch $NomeDuplicado
    Case "", "Unknown" ; These are what is returned from the other 2 possibilities
        ; Do what ever you require for a wrong return
    Case Else
        MsgBox(48,"Duplicidade identificada!","Equipamento com UUID duplicado $NomeDuplicado[0]")
        Exit
EndSwitch
Good enough? :)

M23

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

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

MaGRauN,

The simplest way would be to check the return from the function like this:

$NomeDuplicado = StringRegExp(FileReadLine($LogX, $l), "(?i)Netbios name\s=\s(.*)," , 3)
Switch $NomeDuplicado
    Case "", "Unknown" ; These are what is returned from the other 2 possibilities
        ; Do what ever you require for a wrong return
    Case Else
        MsgBox(48,"Duplicidade identificada!","Equipamento com UUID duplicado $NomeDuplicado[0]")
        Exit
EndSwitch
Good enough? :)

M23

 

Thanks again.

Did not work.

I forget to talk one thing.

Have others lines in the log file, and using you CASE example, will return a not array variable.

I attached tree log files examples

Windows 7 OSD.zip

Link to comment
Share on other sites

  • Moderators
  • Solution

MaGRauN,

That is happening because you have lines in those files without "Netbios = " so there is no return. If you do not specify the correct starting parameters in your questions then the code you get is unlikely to work - something to remember in future. ;)

This runs correctly on the 3 files you posted:

#include <Constants.au3>

For $i = 1 To 3
    ; Open the file
    $hFile = FileOpen("Possibility" & $i & ".log")
    ; Now loop through the file - much quicker to let Autoit do the counting for you
    While 1
        ; Read the next line
        $sLine = FileReadLine($hFile)
        ; And exit the loop when we get to EOF
        If @error = -1 Then ExitLoop
        ; Extract the required text
        $aNetbios = StringRegExp($sLine, "(?i)Netbios name\s=\s(.*)," , 3)
        ; Check we have an array - ie there was a "Netbios = " in the line
        If IsArray($aNetBios) Then
            ; And now check
            Switch $aNetBios[0]
                    Case "", "Unknown"
                        ; Do nothing
                    Case Else
                        MsgBox($MB_SYSTEMMODAL, "Found NetBios", $aNetbios[0])
            EndSwitch
        EndIf
    WEnd
    ; Close the file
    FileClose($hFile)
    ; And go around for the next one
Next
All clear now? :)

M23

Edited by Melba23
Added clarity - I hope!

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

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

MaGRauN,

That is happening because you have lines in those files without "Netbios = " so there is no return. If you do not specify the correct starting parameters in your questions then the code you get is unlikely to work - something to remember in future. ;)

This runs correctly on the 3 files you posted:

#include <Constants.au3>

For $i = 1 To 3
    ; Open the file
    $hFile = FileOpen("Possibility" & $i & ".log")
    ; Now loop through the file - much quicker to let Autoit do the counting for you
    While 1
        ; Read the next line
        $sLine = FileReadLine($hFile)
        ; And exit the loop when we get to EOF
        If @error = -1 Then ExitLoop
        ; Extract the required text
        $aNetbios = StringRegExp($sLine, "(?i)Netbios name\s=\s(.*)," , 3)
        ; Check we have an array - ie there was a "Netbios = " in the line
        If IsArray($aNetBios) Then
            ; And now check
            Switch $aNetBios[0]
                    Case "", "Unknown"
                        ; Do nothing
                    Case Else
                        MsgBox($MB_SYSTEMMODAL, "Found NetBios", $aNetbios[0])
            EndSwitch
        EndIf
    WEnd
    ; Close the file
    FileClose($hFile)
    ; And go around for the next one
Next
All clear now? :)

M23

 

 

Now it is completely clear.

Using a real log, more than 1000 lines, reduces from 7~12 seconds to minus of 1 second.

Thanks again.

Here is the full code:

#include <WindowsConstants.au3>
$Splash = GUICreate("GetLog tool", 176, 87, -1, -1, BitOR($WS_SYSMENU,$WS_POPUP))
$Loading = GUICtrlCreateLabel("Loading", 54, 35, 68, 17)
$Group1 = GUICtrlCreateGroup("", 4, -4, 169, 90)
GUISetState(@SW_SHOW)
#include <file.au3>

TraySetState(2)

;Check if has a local valid IP.
$IP = StringLeft(@IPAddress1,3)
if $IP = "169" or $IP = "127" Then
    GUISetState(@SW_HIDE)
    MsgBox(16, "Invalid IP.", "Please check your network connection.")
    Exit
EndIf

;First place used to store log file
;Check on $LogX if have information about know machine GUID
$LogX = FileOpen(@ScriptDir & "\smsts.log",0)
if $LogX = 1 Then
    While 1
        Local $line = FileReadLine($LogX)
        If @error = -1 Then ExitLoop
        $NomeDuplicado = StringRegExp($Line, "(?i)Netbios name\s=\s(.*)," , 3)
        If IsArray($NomeDuplicado) Then
            Switch $NomeDuplicado[0]
                Case "", "Unknown"
                Case Else
                    GUISetState(@SW_HIDE)
                    MsgBox(48,"Know UUID", "UUID is KNOW for machine " & $NomeDuplicado[0])
                    Exit
            EndSwitch
        EndIf
    WEnd
EndIf

;Get informations abour motherboard, Manufacturer, and others...
Dim $Obj_WMIService = ObjGet('winmgmts:\\' & @ComputerName & '\root\cimv2');
If (IsObj($Obj_WMIService)) And (Not @error) Then
    Dim $Col_CS = $Obj_WMIService.ExecQuery('select * from Win32_ComputerSystem')
    Local $Obj_CS
    For $Obj_CS In $Col_CS
        $Hostname = $Obj_CS.Name
        $Fabricante =$Obj_CS.Manufacturer
        $Modelo = $Obj_CS.Model
    Next
    Dim $Col_BB = $Obj_WMIService.ExecQuery('select * from Win32_BaseBoard')
    Local $Obj_BB
    For $Obj_BB In $Col_BB
        $Motherboard = $Obj_BB.Product
    Next
    Dim $Col_CSP = $Obj_WMIService.ExecQuery('select * from Win32_ComputerSystemProduct')
    Local $Obj_CSP
    For $Obj_CSP In $Col_CSP
        $UUID = $Obj_CSP.UUID
    Next
    Dim $Col_NAC = $Obj_WMIService.ExecQuery('select * from Win32_NetworkAdapterConfiguration')
    Local $Obj_NAC
    For $Obj_NAC In $Col_NAC
        $MAC = $Obj_NAC.MACAddress
    Next
EndIf

;Define place to capture log files and store file informations.
$RootPath = (@ScriptDir & "\"& $Hostname & "_Logs")

;Store informations obtained from WMI query
$String = ("Hostname: " & $Hostname & @CRLF & "Manufacturer: " & $Fabricante & @CRLF & "Model: " & $Modelo & @CRLF & _
"MotherBoard: " & $Motherboard & @CRLF & "UUID: " & $UUID & @CRLF & "MAC: " & $MAC & @CRLF & "IP: " &  @IPAddress1)

;Copyfolder function obtained from Chimaera (http://www.autoitscript.com/forum/topic/147305-using-a-progress-in-a-gui/)
func _CopyFolder($sSourceFolder,$sDestFolder)
    dirremove($sDestFolder,1)
    local $iSourceSize = DirGetSize($sSourceFolder), $iDestSize
    local $pid = Run(@AutoItExe & ' /AutoIt3ExecuteLine "DirCopy(''' & $sSourceFolder & ''', ''' & $sDestFolder & ''')"')
    local $ipct
    ProgressOn("Copiando " & $sSourceFolder , "Por favor aguarde...")
    Do
        $iDestSize = dirgetsize($sDestFolder)
        $ipct = int(($iDestSize/$iSourceSize)*100)
        ProgressSet($ipct,$ipct & '% concluído...')
        sleep(20)
    Until not ProcessExists($pid)
    ProgressOff()
endfunc

;All folder that may have recorded logs
local $log[8]
$log[1] = "X:\Windows\temp\SMSTSLog\"
$log[2] = "C:\_SMSTaskSequence\Logs"
$log[3] = "d:\_SMSTaskSequence\Logs"
$log[4] = "C:\Windows\SysWOW64\CCM\Logs\"
$log[5] = "C:\Windows\System32\CCM\Logs\"
$log[6] = "C:\SMSTslog\"
$log[7] = "d:\SMSTslog\"

GUISetState(@SW_HIDE)

;Start log copy
$start = MsgBox(65,"Log capture.","Click OK to start")
Switch $start
    case 2
        Exit
    case 1
        $dirCreate = DirCreate($RootPath)
        if $dirCreate <> 1 then
            MsgBox(16,"Error","Cannote write on" & $RootPath)
            Exit
        Else

            FileWrite($RootPath & "\" & $hostname & ".txt", $String)
            FileWrite($RootPath & "\Folders.txt", "Log 1 = " & $log[1] & @CRLF & "Log 2 = " & $log[2] & @CRLF & _
            "Log 3 = " & $log[3] & @CRLF & "Log 4 = " & $log[4] & @CRLF & "Log 5 = " & $log[5] & @CRLF & "Log 6 = " & $log[6] & @CRLF & "Log 7 = " & $log[7])

            ;Start copy, if its exists .
            for $x = 1 to 7
                if FileExists($log[$x]) Then
                    _CopyFolder($log[$x],$RootPath & "\Backup_Log" & $x)
                EndIf
            Next
        EndIf
    EndSwitch


MsgBox(0,"Success","All log files captured on" & $RootPath)
Exit

I use it on System Center 2007 OSD, to obtain log on client side.

Everything works faster now.

Any others thing sugests?

Thank you again.

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...