Search for username inside a UNC path in a text file

0

I got a log file where I want to extract the username on a line where it says ERROR 5.

Example:

2018/04/13 10:48:04 ERROR 5 (0x00000005) Copying File \\myserver\shares\johnsmith\My Documents\examplefile.txt

I want to find the string "johnsmith" and put it in a new text file. My idea was to search for ERROR 5 and then find the string in between the fourth and the fifth "\"-letter.

I've found this while googling:

(get-content C:\temp\testlog.txt)  | % { 
    if ($_ -match "ERROR 5 (0x00000005) Copying File \\myserver\shares\ (.*)") { 
        $name = $matches[1]
        echo $name
    }
}

But doesn't really work.

Can anyone give me any clues what functions to use?

powershell
search
asked on Stack Overflow Apr 20, 2018 by naikon • edited Apr 20, 2018 by Vadim Kotov

1 Answer

2

Assuming the file path is always as described, this should give you the names, files and error codes for any matching lines it finds in the log file:

Get-Content C:\temp\testlog.txt  |
    ForEach-Object { 
        if ($_ -match "^.*ERROR (?<ErrorCode>(\d+)) \(0x\d+\) Copying File \\\\myserver\\shares\\(?<UserName>\w+)\\My Documents\\(?<FileName>.*)$") 
        { 
            [PsCustomObject]@{
                UserName = $matches.UserName;
                FileName = $matches.FileName;
                ErrorCode = $matches.ErrorCode
        }
    }
}

Output looks like this:

UserName  FileName        ErrorCode
--------  --------        ---------
johnsmith examplefile.txt 5        
marysmith examplefile.txt 5        
adamsmith examplefile.txt 5        
philsmith examplefile.txt 5 

To capture just the user names to file, modify the code to this:

Get-Content .\testlog.txt  |
    ForEach-Object { 
        if ($_ -match "^.*ERROR (?<ErrorCode>(\d+)) \(0x\d+\) Copying File \\\\myserver\\shares\\(?<UserName>\w+)\\.*$") 
        { 
            $matches.UserName
        }
    } | Out-File .\UserNames.txt
answered on Stack Overflow Apr 20, 2018 by boxdog • edited Apr 20, 2018 by boxdog

User contributions licensed under CC BY-SA 3.0