abs786123
abs786123

Reputation: 609

JSON file with PowerShell loop through

I am faced with a task convert 1 or more CSV files to JSON.

I have been able to do that with the following command:

Import-Csv "File1.csv" |
    ConvertTo-Json -Compress |
    Add-Content -Path "File1_output.JSON"

However, this only does one file at a time and you have to enter the name of the file manually.

To give you a background, say I have 2x CSV file, one called File1.csv and another File2.csv, what I would like to loop through all .csv files in the Documents folders and created a .json output file with the name appended to it.

Ideally I would like to call it as a .ps1 file or even a command line bat file as SSIS will be calling it ultimately.

Upvotes: 0

Views: 511

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200493

Use Get-ChildItem for enumerating files, and a loop for processing the enumerated files.

Something like this should work for converting all CSVs in the current working directory:

Get-ChildItem -Filter '*.csv' | ForEach-Object {
    Import-Csv $_.FullName |
        ConvertTo-Json -Compress |
        Set-Content ($_.Basename + '_output.json')
}

Note that this will convert each file individually. If you want to combine all CSVs into a single JSON document you could probably eliminate the loop

Get-ChildItem -Filter '*.csv' |
    Import-Csv |
    ConvertTo-Json -Compress |
    Set-Content 'output.json'

at least as long as the CSVs have the same columns.

Otherwise you need to define the desired structure of the resulting JSON file first, and then merge the data from the CSVs in a way that conforms to the desired output format.

Upvotes: 2

Related Questions