Last active
July 16, 2021 02:34
-
-
Save cjkoester/5bd2fced5c6d637e09e0 to your computer and use it in GitHub Desktop.
PowerShell script that loops through all CSV files in a folder, selects the desired columns, then outputs the files to a separate folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ------------------------------------------------------------------------ | |
# 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment