# ------------------------------------------------------------------------
# NAME: CSV_SelectColumns.ps1
# AUTHOR: Chris Koester
# DATE: 11/2/2015
#
# KEYWORDS: CSV, text, text file
#
# COMMENTS: This script is used to loop through all CSV files in a folder,
# select the desired columns, then output the files to a separate folder.
#
# DIRECTIONS: Enter the source/destination folder paths and the
# desired columns as variable values below.
#
# REFERENCES:
# http://blogs.technet.com/b/heyscriptingguy/archive/2011/10/17/easily-remove-columns-from-a-csv-file-by-using-powershell.aspx
# ------------------------------------------------------------------------
# Folder containing source CSV files. Be sure to include a backslash after the folder.
$folderPath = 'C:\CSV_Source\'
# Destination folder for the new files. Be sure to include a backslash after the folder.
$folderPathDest = 'C:\CSV_Destination\'
# Desired columns - enclose in single quotes.
$desiredColumns = 'Column1','Column2', 'Column3','Column4','Column5'
# Generate a list of all files in the folder and pipe it to ForEach-Object
Get-ChildItem $folderPath -Name |
# Loop through each file
ForEach-Object {
# Combines source folder path and file name
$filePath = $folderPath + $_
# Combines destination folder and file name
$filePathdest = $folderPathDest + $_
# Imports CSV file, selects desired columns, and then exports as CSV to the desired destination
Import-Csv $filePath | Select $desiredColumns |
Export-Csv -Path $filePathDest –NoTypeInformation
}
Select Columns from CSV Files with PowerShell
Select Columns from CSV Files with PowerShell and output the results to a new set of files.