1
votes

Any help greatly appreciated.

I have a folder that contains 30+ folders which each have a .txt file that I can search for using:

Get-ChildItem -Filter *.txt -Recurse

I want to read the contents of each .txt file discovered and output the contents int a new .csv file on my desktop that also includes the directory of each .txt file contents being displayed.

The question is twofold,

  1. how to use pipe and powershell commands to read/show all the words in the files.

  2. how to create the csv data that will output both the directory name and the contents of the .txt files.

I can already pipe results to:

c:\desktop\test.csv -Encoding ascii -noTypeInformation

1

1 Answers

2
votes

The following script reads all .txt files within a specific directory, stores the full filename and path as well as the files content into an array and saves it as a csv.

$csvOut = @()
Get-ChildItem -LiteralPath C:\temp -Filter *.txt -File -Recurse | foreach {

    $fileData = @{
        "File"=$_.FullName;
        "Content"=(Get-Content -LiteralPath $_.FullName -Raw)
    }
    $csvOut += (New-Object psobject -Property $fileData)
}

$csvOut | Export-Csv -LiteralPath "C:\temp\csvout.csv" -NoTypeInformation