6401integramandj

Noob here, need help with lines and columns

3 posts in this topic

I am very new to Autoit and pretty new to scripting altogether.I have a PowerShell script that pulls owner info from folders on our file share server. There are 3 owners for every folder, Domain Admin, User setup for network scanning and the user. I am trying to copy the username only from this txt file. I have gotten as far as to being able to read the lines in the txt file but can't seem to read the columns. This is what i have so far.

#include <File.au3>

$file = "c:\test01.txt"
FileOpen($file, 0)

For $i = 5 to _FileCountLines($file)
    $line = FileReadLine($file, $i)


 msgbox(0,'','the line ' & $i & ' is ' & $line & 'and the column is')
Next
FileClose($file)

 

This is the outcome.....
2016-12-27 16_58_44-C__Users_dpg_Desktop_New Text Document.au3 - SciTE.png

This is the txt file

2016-12-27 17_06_11-test01.txt - Notepad.png

I am trying to copy the ABC part without the MyDomain\. I know it's line 5 and columns 11-14 of the txt file but i can't figure out how to read it. I hope i'm explaining this correctly. 

Share this post


Link to post
Share on other sites



You're close, but they're not columns in AutoIt. A string is a string in AutoIt and cannot be treated as an array, unless you split it.

A couple of things to note. Don't use a variable used in a for loop outside the for loop. I.e., if you use For $i = n and $i was not declared prior to the for loop, it's bad practice. If you're going to read multiple lines from a file you're better off reading it once and store the contents in an array.

Hopefully this helps

#include <Array.au3>
#include <File.au3>

Global $aFileContents = Null
Global $aUsers[0]

CreateTest01Txt()

; Read the contents of the test01.txt file into an array
; Using _FileReadToArray because I don't like the count in the [0] element from FileReadToArray
_FileReadToArray(@ScriptDir & "\test01.txt", $aFileContents, $FRTA_NOCOUNT)

_ArrayDisplay($aFileContents, "File Contents")

; Go through every line of the file (every row of the array)
For $i = 0 to UBound($aFileContents) - 1
    Local $sUser = Null
    
    ; If the MyDomain\ is in this line
    If (StringInStr($aFileContents[$i], "MyDomain\")) Then
        ; Extract the username fromo the line 
        $sUser = StringRight($aFileContents[$i], StringLen($aFileContents[$i]) - StringInStr($aFileContents[$i], "\"))
        ; and add it to the $aUsers array
        _ArrayAdd($aUsers, $sUser)
    EndIf
Next

_ArrayDisplay($aUsers, "Users")

FileDelete(@ScriptDir & "\test01.txt")

Func CreateTest01Txt()
    Local $hFile = FileOpen(@ScriptDir & "\test01.txt", $FO_OVERWRITE)

    If ($hFile) Then
        FileWrite($hFile, "#TYPE System.Security.Principal.SecurityIdentifier" & @CRLF & _
                        "BinaryLength,AccountDomainSid,Value" & @CRLF & _
                        "Some Fill In Text" & @CRLF & _
                        ",,MyDomain\Domain Admins" & @CRLF & _
                        ",, MyDomain\ABC" & @CRLF & @CRLF & @CRLF & @CRLF & @CRLF & @CRLF & _
                        ";ABC=Username")
        FileClose($hFile)
    EndIf
EndFunc

 

Share this post


Link to post
Share on other sites

@6401integramandj

Welcome to the forums.

Here are a few methods manipulating strings.

(Don't worry about the regular expressions (RegExp) examples if you don't understand them. You are not alone. )

#include <FileConstants.au3>

CreateTest01Txt()

$sFile = FileRead("test01.txt")

; ================= StringMid with StringInStr on @CR of 4th line ========
$iStartFifthLine = StringInStr($sFile, @CR, 0, 4) + 2 ; 2 is for the 2 characters, @CR and @LF, at end of line #4
$iEndFifthLine = StringInStr($sFile, @CR, 0, 5)
ConsoleWrite(StringMid($sFile, $iStartFifthLine + 11, $iEndFifthLine - ($iStartFifthLine + 11)) & @CRLF) ; 11 is for first 11 characters on line #5.
; ========================================================================

;Or

; ================== StringMid with  StringInStr on 2nd occurrence of "\" in file =================
$iStartOfRequiredCharacters = StringInStr($sFile, "\", 0, 2) + 1 ; Find second occurring "\" character.
;                                                                  And, 1 is for the first character after the found "\" character.
ConsoleWrite(StringMid($sFile, $iStartOfRequiredCharacters, $iEndFifthLine - $iStartOfRequiredCharacters) & @CRLF)
; =================================================================================================

;Or

; ============ RegExp 4 lines then match last occurrence of "\" on that line. =======
ConsoleWrite(StringRegExpReplace($sFile, "(?:\V*\v+){4}.+\\(.+)(?s).*", "$1") & @CRLF)
; "(?:\V*\v+){4}.+\\" - Match the first 4 lines, "(?:\V*\v+){4}", (non-capture group, no backreference), and all the characters,
;                       except linefeeds, on the next (5th) line, up to and including the last "\" character on that line., ".+\\".
; "(.+)" - Capture all characters that are not linefeeds. This is the first capture group and is referenced to by
;          backreference 1, "\1" or "$1" or "${1}".
; "(?s)" - From here on when matching characters the dot, ".", will also match linefeed characters.
; ".*" - Match all characters (including the linefeed at the end of the fifth line) to the end of the file.
; Parameter "replace"  = "$1" - As the entire file is matched, the text of the entire file is replaced with backreference 1.
; ===================================================================================

;Or

; ================= RegExp match to last occurrence of "\" in file =================
ConsoleWrite(StringRegExpReplace($sFile, "(?s).+\\(\V+).*", "\1") & @CRLF)
; "\V" - Matches any character that is not a vertical whitespace character (a linefeed).
; ==================================================================================

;Or

; =============== RegExp match to last occurrence of "MyDomain\\" in file ==========
ConsoleWrite(StringRegExpReplace($sFile, "(?s).+MyDomain\\(\V+).*", "${1}") & @CRLF)
; =================================================================================

FileDelete(@ScriptDir & "\test01.txt")


Func CreateTest01Txt()
    Local $hFile = FileOpen(@ScriptDir & "\test01.txt", $FO_OVERWRITE)

    If ($hFile) Then
        FileWrite($hFile, "#TYPE System.Security.Principal.SecurityIdentifier" & @CRLF & _
                "BinaryLength,AccountDomainSid,Value" & @CRLF & _
                "Some Fill In Text" & @CRLF & _
                ",,MyDomain\Domain Admins" & @CRLF & _
                ",,MyDomain\ABC" & @CRLF & @CRLF & @CRLF & @CRLF & @CRLF & @CRLF & _
                ";ABC=Username")
        FileClose($hFile)
    EndIf
EndFunc   ;==>CreateTest01Txt

#cs ; Returns:-
ABC
ABC
ABC
ABC
ABC
#ce

 

2 people like this

Share this post


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

  • Similar Content

    • TheDcoder
      By TheDcoder
      Hello
      I am relatively new to the world of Microsoft Office and the Excel UDF.
      I am trying to loop through every row in a spreadsheet and get the text/values from each column in the given row... so far I have looked into the Help file for the Excel UDF and the wiki page for Excel UDF but I have no idea about how this is done ... This is all I have in my script:
      Global $oExcel = _Excel_Open(False, False, False, False, True) Global Const $sSpreadsheet = @ScriptDir & '\data.xlsx' Global $oSpreadsheet = _Excel_BookOpen($oExcel, $sSpreadsheet, True, False) ; ... I am placing my bet on the _Excel_Range functions... especially _Excel_RangeRead. I don't know how $vRange works so I would be glad if someone can point me in the right direction . What I would ideally like is to get all of the contents of the spreadsheet (it's just a normal text one) in a 2D array.
      Thanks in Advance!
    • tezhihi
      By tezhihi
      I have a file (see attached file) with a string all line and this problem on here is I want to separate all $00:, $03:, $10:, $20:, $25:, $30:, $40:, $45:, $110:, $115:, $120: and $T. It's mean that each $ with value start a new line ( a new paragraph). I tried with Regular Expression in notepad++ ex:
      Find ($00:, $01:, $03: and so on) with regex (\$)([0-9]+): and replace is \r\n\1\2 (I think \r\n is @CRLF (not sure :() ) Find $T with regex (\$T)(.*?)(\$T) and replace is \1\2\r\n\3 When I try these regex to replace in notepad on StringRegexReplace the results is incorrect . I have read some example simple about regex. Please advise me how to do that with some example on autoit . The result will be in attached photo. Thanks 
      ahihi.txt

    • LWC
      By LWC
      I import CSV files which have various headers.
      Is there a way to simply keep only the ones I need and in the order I need them in?
      For example, if the array's first row's values are Foo Bar Test This, then I want to turn them to Foo This Bar.
      Here's how I do it "manually" with _ArrayColDelete and _ArraySwap, but I want to use something smarter like rearrange($aArray, ["Foo", "This", "Bar"]):
      #include <Array.au3> Local $aArray[4][4] = [["Foo", "Bar", "Test", "This"], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] _ArrayDisplay($aArray, "Original") _ArrayColDelete($aArray, 2) ;2 stands for Test, but next time Test might not be 2, but it will still be called "Test" _ArraySwap($aArray, 1, 2, true) ;1 and 2 might be different next time, but their names will remain _ArrayDisplay($aArray, "Modified") If it helps, I do the same thing in VBA based on Sub Reorganize_columns  (the second/alternative example in that page).
    • PINTO1927
      By PINTO1927
      Hello guys, I would have the need to import into the GUICtrlCreateListView all * .txt files in a folder. The * .txt files contain all of the same formatting separated by "|", the script should go on every single file and bring me back the result in the GUICtrlCreateListView. For now I only managed to upload a single file * .txt into the GUICtrlCreateListView with this code:
      Case $Button_Find $File_txt = "\\cond\UPDATE\test.txt" Dim $Array_List _FileReadToArray($File_txt, $Array_List) $Limit_Array = UBound($Array_List) - 1 For $i = 1 To $Limit_Array $All_Box = String($Array_List[$i]) GUICtrlCreateListViewItem($All_Box, $List) Next For $i2 = 0 To _GUICtrlListView_GetColumnCount($List) _GUICtrlListView_SetColumnWidth($List, $i2, $LVSCW_AUTOSIZE_USEHEADER) Next
    • PINTO1927
      By PINTO1927
      Hi Guys,
      I'm working on this project:
      $Import = GUICtrlCreateButton("Import", 15, 175, 90, 40, $WS_GROUP) $List = GUICtrlCreateListView("Name|Address|E-mail", 15, 220, 400, 363, $LVS_SORTDESCENDING) $Item1 = GUICtrlCreateListViewItem("test|test|test", $List) GUISetState(@SW_SHOW, $GUI) While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE, $Exit Exit Case $Import $Table_Import = FileOpenDialog("Import list '*.txt'", @DesktopDir & "\", "Text (*.txt)") If @error Then ContinueLoop GUICtrlSetData($Item1, $Table_Import) In the text file the fields are delimited with "|" and the values are not in the same row but one below the other.
      However in the txt file the sum of the values may change.
      Can you help me?
      Thank's