PowerShell Training · Topic 15

Comparar dos CSV y encontrar diferencias

Un ejercicio práctico para ver qué empleados, registros o IDs aparecen en una lista y no en otra.

Compare two csv files and find differences

A hands-on exercise to see which employees, records, or IDs appear in one list but not another.

⚠️ 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 15

El objetivo es comparar un CSV viejo contra uno nuevo para identificar altas, bajas o diferencias de IDs.

01 · Crear CSV viejo/nuevo
02 · Comparar IDs
03 · Reportar diferencias
Idea central: Comparar versiones antes de procesar evita sorpresas en cargas y reportes.

Topic 15 Objective

The goal is to compare an old CSV against a new one to identify additions, removals, or ID differences.

01 · Create old/new CSV
02 · Compare IDs
03 · Report differences
Core idea: Comparing versions before processing avoids surprises in uploads and reports.

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 15"

Qué vamos a aprender

  • Crear dos versiones de una lista.
  • Usar Compare-Object.
  • Interpretar SideIndicator.
  • Clasificar nuevos y removidos.
  • Exportar control de cambios.

What you will learn

  • Create two versions of a list.
  • Use Compare-Object.
  • Interpret SideIndicator.
  • Classify added and removed records.
  • Export change control.
01

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 15 - Script 1
# Create old and new CSV files
# ======================================================

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

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

$OldPath = Join-Path $DataPath "old.csv"
$NewPath = Join-Path $DataPath "new.csv"

$Old = @(
    [PSCustomObject]@{ Employee_ID = "10001"; Name = "John Smith" },
    [PSCustomObject]@{ Employee_ID = "10002"; Name = "Maria Garcia" },
    [PSCustomObject]@{ Employee_ID = "10003"; Name = "Carlos Rivera" },
    [PSCustomObject]@{ Employee_ID = "10004"; Name = "Ana Lopez" }
)

$New = @(
    [PSCustomObject]@{ Employee_ID = "10002"; Name = "Maria Garcia" },
    [PSCustomObject]@{ Employee_ID = "10003"; Name = "Carlos Rivera" },
    [PSCustomObject]@{ Employee_ID = "10004"; Name = "Ana Lopez" },
    [PSCustomObject]@{ Employee_ID = "10005"; Name = "Robert Lee" }
)

$Old | Export-Csv $OldPath -NoTypeInformation
$New | Export-Csv $NewPath -NoTypeInformation

Write-Host "Old and new CSV files created:"
Write-Host $OldPath
Write-Host $NewPath
02

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 15 - Script 2
# Compare two CSV files by Employee_ID
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 15"
$OldPath = Join-Path $BasePath "Data\old.csv"
$NewPath = Join-Path $BasePath "Data\new.csv"

$Old = Import-Csv $OldPath
$New = Import-Csv $NewPath

Compare-Object $Old.Employee_ID $New.Employee_ID |
Select-Object InputObject, SideIndicator
Nota: revisa siempre el resultado en una carpeta de práctica antes de adaptar el patrón a datos reales.
Note: always review the result in a practice folder before adapting the pattern to real data.
03

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 15 - Script 3
# Export difference report
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 15"
$OldPath = Join-Path $BasePath "Data\old.csv"
$NewPath = Join-Path $BasePath "Data\new.csv"
$ReportPath = Join-Path $BasePath "Reports\CSV_Differences_Report.csv"

$Old = Import-Csv $OldPath
$New = Import-Csv $NewPath

$Differences = Compare-Object $Old.Employee_ID $New.Employee_ID |
ForEach-Object {
    [PSCustomObject]@{
        Employee_ID = $_.InputObject
        Change_Type = if ($_.SideIndicator -eq "=>") { "Added in new CSV" } else { "Removed from new CSV" }
    }
}

$Differences | Export-Csv $ReportPath -NoTypeInformation

Write-Host "Differences report created:"
Write-Host $ReportPath
$Differences | Format-Table -AutoSize

Explicación simple del script

  • $Old.Employee_ID toma los IDs del archivo viejo.
  • $New.Employee_ID toma los IDs del archivo nuevo.
  • Compare-Object compara ambas listas.
  • => indica que aparece en el nuevo.
  • <= indica que aparece en el viejo.

Simple script explanation

  • $Old.Employee_ID takes IDs from the old file.
  • $New.Employee_ID takes IDs from the new file.
  • Compare-Object compares both lists.
  • => means it appears in the new file.
  • <= means it appears in the old file.

Ejemplo esperado

Entrada / CasoResultado
10001Removed from new CSV
10005Added in new CSV

Expected example

Input / CaseResult
10001Removed from new CSV
10005Added in new CSV

Conclusión

Este topic enseña control de cambios básico: identificar qué registros aparecen o desaparecen entre dos versiones de una lista.

Lección clave: Comparar versiones antes de procesar evita sorpresas en cargas y reportes.

Conclusion

This topic teaches basic change control: identifying which records appear or disappear between two versions of a list.

Key lesson: Comparing versions before processing avoids surprises in uploads and reports.