NobleMan
NobleMan

Reputation: 515

Add name of file in column within csv being exported

I am getting the info I need from the files, but I need to have a column that shows the actual log that it is pulling it from.

Get-ChildItem -recurse -filter *.log | 
    get-content | select-string -pattern "dummy" | 
    group path | select name | export-csv "c:\temp\kent.csv"

I am looking for something like this per line: Two columns:

Name of log location : c:\temp\logs\1.log

Reference of the DUMMY remark in log : http://dummy.CORPORATE.LOCAL/SMS_DP_SMSPKG$/bf91665c-4e7b-441a-8bda-87d60a5b8bbe]LOG]!>

Upvotes: 0

Views: 83

Answers (2)

Matt
Matt

Reputation: 46710

One crux of your code is that you are breaking the connection to the source file by using Get-Content and is why you should be seeing "InputStream" in your output. Select-String can take file objects from the pipeline directly so there is no need to convert them to string array first.

$path = "C:\temp"
$pattern = "dummy"
$outputPath = "c:\temp\kent.csv"
Get-ChildItem $path -Recurse -Filter *.txt | Select-String -Pattern $pattern -SimpleMatch | 
    Select-Object Path,Line | Export-Csv $path -NoTypeInformation

I also used -SimpleMatch since regex is supported and your sample does not use it.

Upvotes: 1

JohnLBevan
JohnLBevan

Reputation: 24430

Try this:

Get-ChildItem -recurse -filter *.log `
| %{$LogFile = $_.FullName; $_} `
| get-content `
| select-string -pattern "dummy" `
| group path `
| select name, @{N='LogFileName'; E={$LogFile}} `
| export-csv "c:\temp\kent.csv"
  • You can ignore the backticks and new lines; those are just to make the code simpler to read here.

  • | %{$LogFile = $_.FullName; $_} - Records the filename in a variable called $LogFile, then passes the content that it received on to the next element in the pipeline.

  • | select name, @{N='LogFileName'; E={$LogFile}} - I've added a new column with Name LogFileName and value (expression) taken from the $LogFile variable populated earlier.

Upvotes: 0

Related Questions