0

I'm struggling trying to pass a variable not only throughta pipeline but a foreach.

I have in multiples directories a lot of csv files (some with the same name) adding some data to it.

I want to generate a unique csv file merging all files with same name but with one conditions:

  • Add an extra column with the date from the above folder I picked up the data

I'm just missing how to pass the variable $outfile to the end of the pipeline (to the Export-CSV function).

$mainPath="C:\\....";
$outFilePath = "C:\\Users....\\";
$dateFolder="";
$inputDelimiter=';'
$outputDelimiter=','

$filter="*.csv";
$outFile = "";

Get-ChildItem $mainPath -Recurse -Include $filter `
| %{
        $dateFolder = (Split-Path (Split-Path $_.DirectoryName -Parent )-Leaf)
        $outfile = Split-Path $_ -Leaf
        Import-Csv $_.FullName -Delimiter $inputDelimiter
} `
| Select-Object *,@{Name='Date'; Expression={"$dateFolder"}} `
| Export-Csv $outFilePath$outFile -NoTypeInformation -Delimiter $outputDelimiter

Thanks. Regards. Jose.

1 Answer 1

0

Just move the Select-Object and Export-Csv statements inside the ForEach-Object scriptblock:

Get-ChildItem $mainPath -Recurse -Include $filter `
| %{
        $dateFolder = (Split-Path (Split-Path $_.DirectoryName -Parent )-Leaf)
        $outfile = Split-Path $_ -Leaf
        Import-Csv $_.FullName -Delimiter $inputDelimiter `
        | Select-Object *,@{Name='Date'; Expression={"$dateFolder"}} `
        | Export-Csv "$outFilePath$outFile" -NoTypeInformation -Delimiter $outputDelimiter
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Mathias, thanks for your fast response. It works but breaks something that previously was working... All forlders I have with following structure /20180101/site1 /20180101/site2 /20180101/site3 .... /20180102/site1 /20180102/site2 /20180102/site3 And I need to have this "date" in a column at the end of each csv with the right parent folder. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.