Devinput
Devinput

Reputation: 53

Appending results of string search to existing csv file

I would like to search multiple folders for files containing a certain string. The name of each folder is listed in a csv file (thelist.csv) that has a single header (List1). I’d like to append the results of my search to thelist.csv to add a column for FileName (Result1) and Directory (Result2). I'm attempting to get into a csv file (or excel sheet) so I can ultimately identify which folders do/don't contain the “TestString.txt” file.

Example Code:

       $csv = Import-Csv  C:\The\Path\thelist.csv -Header List1, Results1, Results2
foreach ($line in $csv) {  
    $Results1= $line.Results1
    $Results2 = $line.Results2
    Get-ChildItem -Path "C:\The\Path" -Filter *TestString* -Recurse | Select List1, Results1, Results2  | Export-csv C:\The\Path\thelist2.csv -NoTypeInformation
} 

My search for the missing string successfully returns results including filename (result1) and directory (result2). However, I'm experiencing issues appending the results to a csv file. Right now my code returns empty values for (List1) from the original list. The only data that exists from the original csv file is the header.

Upvotes: 0

Views: 520

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29003

Your code is trying to pull the properties "List1, Results1, Results2" out of the filenames, without any code to tell it how to do that, so they are empty and blank.

You are trying to do the export inside the loop, deleting the file and overwriting it for each search, so it would only have one result in it.

You might need to handle the case where one search returns multiple matching files, which would need to add new lines to the CSV.

I haven't tried this code, but this kind of approach should be closer to what you want:

# Import from single column file, calling the column 'List1', and process each line:
Import-Csv -LiteralPath C:\The\Path\thelist.csv -Header List1 | ForEach-Object {

    # store line with a name, for use later on
    $Line = $_

    # the folders coming in from the CSV are in the column 'List1', search them
    Get-ChildItem -LiteralPath $Line.List1 -Filter *TestString* -Recurse | ForEach-Object {


        # for each search result TestString.txt, make a hashtable 
        # representing a new line in the output CSV, with the new data,
        # and convert to PS Custom Object so it will work with Export-CSV later on.

        [PSCustomObject]@{
            'List1' = $Line.List1
            'Result1' = $_.Name
            'Result2' = $_.DirectoryName
        }
    }

    # at the end of both loops, export all the results in one go
} | Export-csv C:\The\Path\thelist2.csv -NoTypeInformation

Upvotes: 1

Related Questions