PowerShell Training · Topic 11

Estandarizar columnas de un CSV

Un ejercicio práctico para reordenar columnas, renombrarlas y exportar solo los campos necesarios.

Standardize CSV columns

A hands-on exercise to reorder columns, rename them, and export only the required fields.

⚠️ Advertencia crítica antes de correr cualquier script

No ejecutes este tipo de script en un ambiente de producción, carpeta real, servidor compartido, unidad de red o sistema institucional sin autorización formal.

PowerShell es una herramienta poderosa: un comando de renombrado masivo puede modificar cientos o miles de archivos en segundos. En una carpeta equivocada, eso puede causar pérdida de trazabilidad, fallos en procesos automáticos, interrupciones operativas o incidentes de ciberseguridad.

Regla obligatoria del training: primero se trabaja con data sintética, luego se valida con una muestra pequeña, después se prueba con -WhatIf cuando aplique, y solo entonces se considera ejecutar en datos reales siguiendo los protocolos de la organización.

  • Permisos: usa solamente carpetas donde tengas autorización explícita.
  • Backups: confirma que exista copia de seguridad o posibilidad real de recuperación.
  • Cybersecurity: cumple las políticas internas, controles de acceso, change management y principios de menor privilegio.
  • Producción: nunca ejecutes scripts masivos directamente sobre producción sin revisión, aprobación y plan de reversa.

⚠️ Critical warning before running any script

Do not run this type of script in a production environment, real folder, shared server, network drive, or institutional system without formal authorization.

PowerShell is a powerful tool: a bulk command can modify hundreds or thousands of files in seconds. In the wrong folder, it can break traceability, disrupt automated processes, create operational issues, or trigger cybersecurity incidents.

Mandatory training rule: start with synthetic data, validate with a small sample, test with -WhatIf when applicable, and only then consider real data while following your organization’s protocols.

  • Permissions: use only folders where you have explicit authorization.
  • Backups: confirm that a backup or real recovery option exists.
  • Cybersecurity: follow internal policies, access controls, change management, and least-privilege principles.
  • Production: never run bulk scripts directly on production without review, approval, and rollback planning.

Objetivo del Topic 11

El objetivo es convertir un CSV desordenado en un archivo limpio y consistente. Vamos a tomar columnas con nombres diferentes, remover campos innecesarios y exportar una versión estándar lista para validación, BI o carga a otro sistema.

01 · Crear CSV crudo
02 · Estandarizar columnas
03 · Verificar CSV limpio
Idea central: limpiar data no siempre significa cambiar valores. Muchas veces el primer paso es controlar la estructura: nombres de columnas, orden y campos requeridos.

Topic 11 Objective

The goal is to convert a messy CSV into a clean and consistent file. We will take columns with different names, remove unnecessary fields, and export a standard version ready for validation, BI, or system upload.

01 · Create raw CSV
02 · Standardize columns
03 · Verify clean CSV
Core idea: cleaning data does not always mean changing values. Many times the first step is controlling the structure: column names, order, and required fields.

Ruta de trabajo

Todo se ejecuta dentro de una carpeta controlada:

Working folder

Everything runs inside a controlled folder:

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 11"

Qué vamos a aprender

  • Crear un CSV crudo con columnas no estandarizadas.
  • Leer data con Import-Csv.
  • Crear columnas calculadas con nombres limpios.
  • Seleccionar solo los campos necesarios.
  • Exportar un CSV limpio con Export-Csv.

What you will learn

  • Create a raw CSV with non-standard columns.
  • Read data with Import-Csv.
  • Create calculated columns with clean names.
  • Select only the required fields.
  • Export a clean CSV with Export-Csv.
01

Script 1 — Crear CSV crudo de práctica

Este script crea un archivo raw.csv con nombres de columnas que no están listos para un proceso formal.

Script 1 — Create practice raw CSV

This script creates a raw.csv file with column names that are not ready for a formal process.

# ======================================================
# Topic 11 - Script 1
# Create a raw CSV with non-standard columns
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 11"
$DataPath = Join-Path $BasePath "Data"

New-Item -Path $DataPath -ItemType Directory -Force | Out-Null

$RawCsvPath = Join-Path $DataPath "raw.csv"

$RawData = @(
    [PSCustomObject]@{ EmpID = "10001"; F_Name = "John"; Last = "Smith"; DeptName = "Finance"; EmailAddress = "john.smith@example.com"; Notes = "Imported from old system" },
    [PSCustomObject]@{ EmpID = "10002"; F_Name = "Maria"; Last = "Garcia"; DeptName = "HR"; EmailAddress = "maria.garcia@example.com"; Notes = "Manual entry" },
    [PSCustomObject]@{ EmpID = "10003"; F_Name = "Carlos"; Last = "Rivera"; DeptName = "IT"; EmailAddress = "carlos.rivera@example.com"; Notes = "Extra column not needed" },
    [PSCustomObject]@{ EmpID = "10004"; F_Name = "Ana"; Last = "Lopez"; DeptName = "Operations"; EmailAddress = "ana.lopez@example.com"; Notes = "Legacy export" }
)

$RawData | Export-Csv -Path $RawCsvPath -NoTypeInformation

Write-Host "Raw CSV created:"
Write-Host $RawCsvPath

Import-Csv $RawCsvPath | Format-Table -AutoSize
02

Script 2 — Estandarizar columnas y exportar CSV limpio

Este script importa el CSV crudo, renombra las columnas mediante propiedades calculadas, reordena los campos y exporta un archivo limpio.

Script 2 — Standardize columns and export clean CSV

This script imports the raw CSV, renames columns using calculated properties, reorders fields, and exports a clean file.

# ======================================================
# Topic 11 - Script 2
# Standardize CSV columns
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 11"
$DataPath = Join-Path $BasePath "Data"

$RawCsvPath = Join-Path $DataPath "raw.csv"
$CleanCsvPath = Join-Path $DataPath "clean.csv"

Import-Csv $RawCsvPath |
Select-Object `
    @{Name="Employee_ID"; Expression={ $_.EmpID }},
    @{Name="FirstName"; Expression={ $_.F_Name }},
    @{Name="LastName"; Expression={ $_.Last }},
    @{Name="Department"; Expression={ $_.DeptName }},
    @{Name="Email"; Expression={ $_.EmailAddress }} |
Export-Csv $CleanCsvPath -NoTypeInformation

Write-Host "Clean CSV created:"
Write-Host $CleanCsvPath
Nota: este script no modifica el archivo original. Crea un nuevo CSV limpio, dejando el crudo disponible para auditoría o comparación.
Note: this script does not modify the original file. It creates a new clean CSV, keeping the raw file available for audit or comparison.
03

Script 3 — Verificar CSV limpio

Este script importa el archivo limpio y muestra las columnas finales para confirmar que la estructura quedó correcta.

Script 3 — Verify clean CSV

This script imports the clean file and displays the final columns to confirm that the structure is correct.

# ======================================================
# Topic 11 - Script 3
# Verify standardized CSV
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 11"
$CleanCsvPath = Join-Path $BasePath "Data\clean.csv"

Write-Host "Clean CSV preview:"
Import-Csv $CleanCsvPath | Format-Table -AutoSize

Write-Host ""
Write-Host "Final columns:"
(Import-Csv $CleanCsvPath | Select-Object -First 1).PSObject.Properties.Name

Explicación simple del script

  • Import-Csv lee el archivo crudo.
  • Select-Object define qué columnas salen en el CSV limpio.
  • @{Name=...; Expression=...} permite renombrar columnas.
  • Export-Csv guarda la nueva versión limpia.
  • -NoTypeInformation evita una línea técnica innecesaria en el CSV.

Simple script explanation

  • Import-Csv reads the raw file.
  • Select-Object defines which columns go into the clean CSV.
  • @{Name=...; Expression=...} allows column renaming.
  • Export-Csv saves the new clean version.
  • -NoTypeInformation avoids an unnecessary technical line in the CSV.

Ejemplo esperado

AntesDespués
EmpIDEmployee_ID
F_NameFirstName
LastLastName
DeptNameDepartment
EmailAddressEmail

Expected example

BeforeAfter
EmpIDEmployee_ID
F_NameFirstName
LastLastName
DeptNameDepartment
EmailAddressEmail

Conclusión

Este topic enseña una base esencial de limpieza de datos: antes de validar, cruzar o cargar información, necesitamos una estructura consistente. Columnas claras y ordenadas reducen errores y hacen que el flujo sea más fácil de auditar.

Lección clave: un CSV limpio empieza por una estructura limpia: campos correctos, nombres estándar y solo la información necesaria.

Conclusion

This topic teaches an essential data cleaning foundation: before validating, matching, or uploading information, we need a consistent structure. Clear and ordered columns reduce errors and make the workflow easier to audit.

Key lesson: a clean CSV starts with a clean structure: correct fields, standard names, and only the necessary information.