Skip to content

Instantly share code, notes, and snippets.

@jworkmanjc
Last active April 13, 2025 15:16
Show Gist options
  • Save jworkmanjc/2150ddac8539728408719cb38a4da77f to your computer and use it in GitHub Desktop.
Save jworkmanjc/2150ddac8539728408719cb38a4da77f to your computer and use it in GitHub Desktop.
renames some CSV headers in a directory recursively
# Define the directory to search for CSV files
$directory = "/Path/To/Your/CSVs"
# Define the old column name and the new column name
$oldColumnName = "middle_name"
$newColumnName = "fiddle_name"
# Get all CSV files in the directory
$csvFiles = Get-ChildItem -Path $directory -Filter *.csv -Recurse
foreach ($file in $csvFiles) {
# Import the CSV file
$csvData = Import-Csv -Path $file.FullName
# Check if the old column name exists
if ($csvData | Get-Member -MemberType NoteProperty | Where-Object { $_.Name -eq $oldColumnName }) {
# Rename the column
$csvData = $csvData | ForEach-Object {
$_ | Add-Member -NotePropertyName $newColumnName -NotePropertyValue $_.$oldColumnName -Force
$_.PSObject.Properties.Remove($oldColumnName)
$_
}
# Export the updated CSV back to the file
$csvData | Export-Csv -Path $file.FullName -NoTypeInformation
Write-Host "Updated column in file: $($file.FullName)"
}
else {
Write-Host "Column '$oldColumnName' not found in file: $($file.FullName)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment