⚠️ 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 12
El objetivo es limpiar espacios al inicio y al final de valores críticos en un CSV. Esto evita que registros aparentemente iguales no coincidan por caracteres invisibles.
Topic 12 Objective
The goal is to trim leading and trailing spaces from critical values in a CSV. This prevents records that look identical from failing to match because of invisible characters.
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 12"
Qué vamos a aprender
- Crear un CSV con espacios ocultos.
- Usar .Trim() en campos críticos.
- Limpiar IDs, nombres, departamentos y emails.
- Exportar una versión limpia.
- Comparar antes y después.
What you will learn
- Create a CSV with hidden spaces.
- Use .Trim() on critical fields.
- Clean IDs, names, departments, and emails.
- Export a clean version.
- Compare before and after.
Script 1 — Crear data sintética
Este script prepara los archivos o datos de práctica necesarios para ejecutar el ejercicio sin tocar información real.
Script 1 — Create synthetic data
This script prepares the practice files or data needed to run the exercise without touching real information.
# ======================================================
# Topic 12 - Script 1
# Create a CSV with hidden spaces
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 12"
$DataPath = Join-Path $BasePath "Data"
New-Item -Path $DataPath -ItemType Directory -Force | Out-Null
$RawCsvPath = Join-Path $DataPath "raw_spaces.csv"
$RawData = @(
[PSCustomObject]@{ Employee_ID = " 10001 "; FirstName = " John "; LastName = " Smith"; Department = " Finance "; Email = " john.smith@example.com " },
[PSCustomObject]@{ Employee_ID = "10002 "; FirstName = " Maria"; LastName = "Garcia "; Department = " HR"; Email = "maria.garcia@example.com " },
[PSCustomObject]@{ Employee_ID = " 10003"; FirstName = " Carlos "; LastName = " Rivera "; Department = " IT "; Email = " carlos.rivera@example.com" }
)
$RawData | Export-Csv -Path $RawCsvPath -NoTypeInformation
Write-Host "Raw CSV with hidden spaces created:"
Write-Host $RawCsvPath
Import-Csv $RawCsvPath | Format-Table -AutoSize
Script 2 — Ejecutar la acción principal
Este script aplica la lógica central del topic y genera el resultado principal del ejercicio.
Script 2 — Run the main action
This script applies the core logic of the topic and generates the main result of the exercise.
# ======================================================
# Topic 12 - Script 2
# Trim spaces from critical fields
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 12"
$DataPath = Join-Path $BasePath "Data"
$RawCsvPath = Join-Path $DataPath "raw_spaces.csv"
$CleanCsvPath = Join-Path $DataPath "clean_trimmed.csv"
Import-Csv $RawCsvPath | ForEach-Object {
[PSCustomObject]@{
Employee_ID = $_.Employee_ID.Trim()
FirstName = $_.FirstName.Trim()
LastName = $_.LastName.Trim()
Department = $_.Department.Trim()
Email = $_.Email.Trim()
}
} | Export-Csv $CleanCsvPath -NoTypeInformation
Write-Host "Trimmed CSV created:"
Write-Host $CleanCsvPath
Script 3 — Verificar o reportar resultados
Este script confirma el resultado final o genera evidencia para revisión.
Script 3 — Verify or report results
This script confirms the final result or generates evidence for review.
# ======================================================
# Topic 12 - Script 3
# Verify trimmed values
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 12"
$CleanCsvPath = Join-Path $BasePath "Data\clean_trimmed.csv"
Import-Csv $CleanCsvPath | Format-Table -AutoSize
Write-Host ""
Write-Host "Employee ID lengths after trim:"
Import-Csv $CleanCsvPath |
Select-Object Employee_ID, @{Name="ID_Length"; Expression={ $_.Employee_ID.Length }} |
Format-Table -AutoSize
Explicación simple del script
- Import-Csv lee el archivo con espacios.
- ForEach-Object procesa cada fila.
- .Trim() remueve espacios antes y después.
- [PSCustomObject] reconstruye la fila limpia.
- Export-Csv guarda el resultado.
Simple script explanation
- Import-Csv reads the file with spaces.
- ForEach-Object processes each row.
- .Trim() removes leading and trailing spaces.
- [PSCustomObject] rebuilds the clean row.
- Export-Csv saves the result.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| 10001 | 10001 |
| john.smith@example.com | john.smith@example.com |
| Finance | Finance |
Expected example
| Input / Case | Result |
|---|---|
| 10001 | 10001 |
| john.smith@example.com | john.smith@example.com |
| Finance | Finance |
Conclusión
Este topic enseña a eliminar uno de los errores más difíciles de ver: espacios ocultos. Un dato puede verse correcto, pero fallar en un cruce si contiene espacios antes o después.
Conclusion
This topic teaches how to remove one of the hardest errors to see: hidden spaces. A value may look correct, but fail in a match if it contains leading or trailing spaces.