choco_linux
choco_linux

Reputation: 153

i want to get particular information from a text file using powershell

I have a log file which I extracted using get-eventlog cmdlet, here is an example of its output:

index      Time      EntryType      source           InstanceID          Message

000        xxxx       error          system            1111           host ip: 55.55.55.55
                                                                      class: tropical
                                                                      state: open
                                                                      name:  contractor_0001

000        xxxx       error          system            1111               host ip: 55.55.55.55
                                                                      class: tropical
                                                                      state: open
                                                                      name:  contractor_0002

000        xxxx       error          system            1111               host ip: 55.55.55.55
                                                                      class: tropical
                                                                      state: open
                                                                      name:  contractor_0003

000        xxxx       error          system            1111               host ip: 55.55.55.55
                                                                      class: tropical
                                                                      state: open
                                                                      name:  contractor_0004

basically I need the name of each person in a list in a text or just output using powershell for example:

contractor_0001

contractor_0002

contractor_0003

contractor_0004

I only need the names, none of the other information.

Upvotes: 0

Views: 187

Answers (2)

Graham Gold
Graham Gold

Reputation: 2485

As others have said, might be better to extract only the info you want, directly from the log file.

However, to answer the question you asked, this'll do it :-

(gc ("C:\yourpath\yourfile.txt")) -match 'name:\s' | foreach {$_.Split(":")[1].Replace(' ','')}

You can pipe it to out-file to write to a file if you want.

Output from my test with your data:

contractor_0001
contractor_0002
contractor_0003
contractor_0004

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

It'd be simpler to extract this information directly from the eventlog:

Get-EventLog "System" -EntryType "Error" -InstanceId 1111 | % {
  $_.Message -replace '[\s\S]*name:\s+(\S+)[\s\S]*','$1'
}

If you're limited to a textfile like the one you showed, you could try with Select-String:

Select-String 'name:\s+(\S+)' input.txt | % { $_.Matches.Groups[1].Value }

Upvotes: 4

Related Questions