I am just starting to learn PowerShell and have run into a hurdle where I'm trying to use gci and import-csv. My goal is to run a script in a folder directory that has numerous subfolders that contain a specific csv file that I would like to import and consolidate the data. These subfolders have additional subfolders that have other file types including csv that I don't have any use for. I am interested in the specific path below. The csv files have a specific header type called location that I care about and have to parse out into a string.
This is my code so far:
$files = gci .\ -Recurse
foreach($file in $files) {
$foldername = $file.Name
$csv = Import-Csv -Path ".\$foldername\$foldername.csv"
foreach ($line in $csv) {
$outputlines = $line.location -split '/'
Export-csv -Path .\Test.csv -NoTypeInformation -Append
}
}
This is the message I get when I run it: cmdlet Export-Csv at command pipeline position 1 Supply values for the following parameters: InputObject:
Can someone please guide me in the right direction on what I'm doing wrong?
As others have commented and strictly speaking,
Export-Csvneeds something to export. However, that's not the only issue.Import-Csvwill return objects based on the data in the csv file. So-splitis likely to provide strange results as it's designed to run against strings and/or arrays of strings.Withstanding the
-splitthat is unlikely to work, you can address consolidation more simply by simply feeding the results from manyImport-Csvcommands to a singleExport-csvcommand:The loop will output a series of strings that are piped to
Import-Csv. So, all the files will get imported and the resulting objects will be streamed toExport-Csvconsolidating everything into$Outputcsvwhich is c:\temp\Output.csv.Note: The use of the
-Directoryparameter. Since you are only leveraging the folder names that should prevent a few errors, particularly for file names that may not exist.If you want to clarify the question with an example of the CSV contents and the desired output we can take this further.