0
votes

I have a batch of csv extension files with JSON format in Content and tried to convert to a delimited format csv using powershell.

Once one JSON file been converted, it needs to be moved to another directory for backup after been converted. The script below works only if import one static file from one directory. I am trying to use "Get-ChildItem | foreach-object", but it doesn't work for some reason. By running this script, all files from raw will be moved to the backup folder straight away, but there is no files been converted in the converted folder.

It feels like the # execute converting script didn't run at all. I'm not too sure if $fromJson = Get-Content -Raw $InputPath | ConvertFrom-Json" works for importing files by loop.

Need help!

working script:

$InputPath ="C:\Users\Desktop\raw\a.csv"

$OutputPath = "C:\Users\Desktop\raw\Converted\$(get-date -f yyyy-MM-ddhhmmssfffff).csv"

$fromJson = Get-Content -Raw $InputPath | ConvertFrom-Json 
& {

# execute converting script

} | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content -path $OutputPath 


Move-Item -path $InputPath -destination "C:\Users\Desktop\raw\backup"



Script with problem:

$InputPath ="C:\Users\Desktop\raw\*.csv"

Get-ChildItem $InputPath| Foreach-Object{
$OutputPath = "C:\Users\Desktop\raw\Converted\$(get-date -f yyyy-MM-ddhhmmssfffff).csv"

$fromJson = Get-Content -Raw $InputPath | ConvertFrom-Json 
& {

# execute converting script

} | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content -path $OutputPath 


Move-Item -path $InputPath -destination "C:\Users\Desktop\raw\backup"

}

1

1 Answers

2
votes

You Need to get all the CSV Files first then cycle through them. The below should work for what you are after.

$CSVFiles = Get-ChildItem -Path "C:\Users\Desktop\raw\" -Filter "*.CSV"
Foreach($File in $CSVFiles) {
    Get-Content -Raw $File.FullName | ConvertFrom-Json 
    & {
        # execute converting script
    } | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Set-Content -path $("C:\Users\Desktop\raw\Converted\$($File.BaseName)_$(get-date -f yyyy-MM-ddhhmmssfffff).csv")
    Move-Item -path $File.FullName -destination "C:\Users\Desktop\raw\backup"
}