Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I have a script below that I want to execute against all .csv files in a directory. I know I can use Get-ChildItems, but how to filter it for only .csv files in .\ and execute my script?

import-csv .\chapters.csv | 
    ConvertTo-Json -Compress | 
    ForEach-Object {$_ -creplace '""NULL""','null'} | 
    Out-File .\chapters.json
share|improve this question

1 Answer 1

up vote 2 down vote accepted

If I understand what you're asking, just use a file glob and pipe the results to Import-CSV **. Use a Foreach-Object loop to capture the base name of each CSV file to use in naming the output files.

Get-ChildItem .\*.csv | Foreach-Object {
  $basename = $_.BaseName
  import-csv $_ | ConvertTo-Json -Compress | Foreach {$_ -creplace '""NULL""','null'} | Out-File ".\$basename.json"
}

BTW, there's no "s" at the end of Get-ChildItem.

share|improve this answer
    
sorry don't mean to glob them in one file, but how to I execute the script per file? So one json file will be generated for each (chapters.csv, authors.csv, books.csv, etc will generate chapters.json, authors.json, books.json). – TruMan1 Jul 12 '13 at 0:11
    
"glob" doesn't mean to collect data into a single file. It's a standard computing term that means to match names (particularly filenames) using wildcards: en.wikipedia.org/wiki/Glob_%28programming%29. Get-ChildItem .\*.csv will select all files with the .csv extension and feed them one by one into the pipeline to be converted to objects by Import-Csv. Did you even try it? – Adi Inbar Jul 12 '13 at 2:02
1  
Actually, I just noticed a problem, which is that the output file is always chapters.json, and it gets overwritten each time, so you'll only have the results from the last CSV file. I'll modify the answer so that the .json files will have the same base names as the .csv files. – Adi Inbar Jul 12 '13 at 2:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.