Skip to content

Instantly share code, notes, and snippets.

@csandfeld
Created September 26, 2015 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csandfeld/2b8c12ccdc5b11e71632 to your computer and use it in GitHub Desktop.
Save csandfeld/2b8c12ccdc5b11e71632 to your computer and use it in GitHub Desktop.
Trim CSV data
Column1 Column2 Column3 Column4 Column5
1nospace 1leadingspace 1trailingspace 1leadingandtrailingspace 1space within
2nospace 2leadingspace 2trailingspace 2leadingandtrailingspace 2space within
# Specify input and output files
$InputCSVFile = '.\input.csv'
$OutputCSVFile = '.\output.csv'
# Import data from CSV
$CSVData = Import-Csv -Path $InputCSVFile
# Run trim() (remove leading and trailing whitespace) on all property values
$CSVTrimmedData = $CSVData | Foreach-Object {
# Foreach property
$_.PSObject.Properties | Foreach-Object {
# Trim the value (remove whitespace)
$_.Value = $_.Value.Trim()
}
# Output the object
Write-Output $_
}
# Export trimmed data to CSV
$CSVTrimmedData | Export-Csv -Path $OutputCSVFile -NoTypeInformation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment