Remover los retornos de carro que los usuarios meten accidentalmente dentro de celdas en Excel y que rompen el formato CSV.
Remove carriage returns that users accidentally enter inside Excel cells and that can break the CSV format.
Este ejercicio es solo para aprendizaje y pruebas. No ejecutes scripts contra datos reales, ambientes de producción, carpetas compartidas, sistemas críticos o repositorios empresariales sin autorización, respaldos, pruebas previas, permisos mínimos, control de cambios y cumplimiento de los protocolos de ciberseguridad de tu organización.
This exercise is for learning and testing only. Do not run scripts against real data, production environments, shared folders, critical systems, or enterprise repositories without authorization, backups, prior testing, least-privilege permissions, change control, and compliance with your organization's cybersecurity protocols.
Limpiar campos de texto que contienen saltos de línea invisibles, tabulaciones o dobles espacios. Este problema aparece con frecuencia cuando un archivo viene de Excel, formularios manuales o comentarios escritos por usuarios.
Clean text fields that contain invisible line breaks, tabs, or double spaces. This problem frequently appears when a file comes from Excel, manual forms, or user-entered comments.
| ID | Nombre | Comentarios |
|---|---|---|
| 1001 | Ana Perez | Documento recibido con salto de línea interno |
| 1002 | John Smith | Comentario copiado desde Excel |
| 1003 | Maria Lopez | Texto con Enter accidental dentro de la celda |
$_.Comentarios = $_.Comentarios -replace "`r|`n", " "
| ID | Comentarios originales | Comentarios limpios |
|---|---|---|
| 1001 | Línea 1 Línea 2 | Línea 1 Línea 2 |
| 1002 | Texto con tabulación | Texto con tabulación limpia |
| 1003 | Comentario con Enter interno | Comentario con Enter interno limpio |
# ==========================================================
# PowerShell Advanced Topic 18
# Clean Invisible Line Breaks Inside Cells
# ==========================================================
$inputFile = "C:\Data\Comentarios.csv"
$outputFile = "C:\Data\Comentarios_Clean.csv"
# Import CSV
$datos = Import-Csv $inputFile
# Clean specific text column
$resultado = foreach ($row in $datos) {
if ($null -ne $row.Comentarios) {
# Remove carriage returns, line feeds, tabs, and extra spaces
$row.Comentarios = $row.Comentarios `
-replace "`r|`n", " " `
-replace "`t", " " `
-replace "\s{2,}", " "
# Trim leading and trailing spaces
$row.Comentarios = $row.Comentarios.Trim()
}
$row
}
# Export clean file
$resultado | Export-Csv $outputFile -NoTypeInformation -Encoding UTF8
Write-Host "Invisible line breaks cleaned successfully."
Write-Host "Output file: $outputFile"Esta versión revisa todas las columnas del CSV y limpia saltos de línea, tabulaciones y espacios excesivos en cualquier campo de texto.
This version scans all CSV columns and cleans line breaks, tabs, and excessive spaces in any text field.
# ==========================================================
# Clean Invisible Characters in All Text Columns
# ==========================================================
$inputFile = "C:\Data\Maestro.csv"
$outputFile = "C:\Data\Maestro_Clean_Text.csv"
$datos = Import-Csv $inputFile
foreach ($row in $datos) {
foreach ($property in $row.PSObject.Properties) {
if ($null -ne $property.Value -and $property.Value -is [string]) {
$property.Value = $property.Value `
-replace "`r|`n", " " `
-replace "`t", " " `
-replace "\s{2,}", " "
$property.Value = $property.Value.Trim()
}
}
}
$datos | Export-Csv $outputFile -NoTypeInformation -Encoding UTF8
Write-Host "All text columns cleaned."
Write-Host "Output file: $outputFile"Este patrón ayuda a prevenir errores silenciosos en archivos CSV. Un salto de línea dentro de una celda puede partir registros, romper cargas automáticas y crear problemas difíciles de detectar en procesos de integración de datos.
This pattern helps prevent silent errors in CSV files. A line break inside a cell can split records, break automated loads, and create hard-to-detect problems in data integration processes.