⚠️ 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 17
El objetivo es unir múltiples CSV con la misma estructura en un solo archivo combinado.
Topic 17 Objective
The goal is to merge multiple CSV files with the same structure into one combined file.
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 17"
Qué vamos a aprender
- Crear archivos separados por departamento.
- Leer varios CSV desde una carpeta.
- Agregar columna de origen.
- Exportar un archivo combinado.
- Validar conteos finales.
What you will learn
- Create files separated by department.
- Read multiple CSV files from a folder.
- Add a source column.
- Export a combined file.
- Validate final counts.
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 17 - Script 1
# Create multiple CSV files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 17"
$ReportsPath = Join-Path $BasePath "Reports"
New-Item -Path $ReportsPath -ItemType Directory -Force | Out-Null
@(
[PSCustomObject]@{ Employee_ID = "10001"; Name = "John Smith"; Department = "Finance" },
[PSCustomObject]@{ Employee_ID = "10002"; Name = "Maria Garcia"; Department = "Finance" }
) | Export-Csv (Join-Path $ReportsPath "finance.csv") -NoTypeInformation
@(
[PSCustomObject]@{ Employee_ID = "10003"; Name = "Carlos Rivera"; Department = "HR" },
[PSCustomObject]@{ Employee_ID = "10004"; Name = "Ana Lopez"; Department = "HR" }
) | Export-Csv (Join-Path $ReportsPath "hr.csv") -NoTypeInformation
@(
[PSCustomObject]@{ Employee_ID = "10005"; Name = "Robert Lee"; Department = "IT" },
[PSCustomObject]@{ Employee_ID = "10006"; Name = "Linda Brown"; Department = "IT" }
) | Export-Csv (Join-Path $ReportsPath "it.csv") -NoTypeInformation
Get-ChildItem $ReportsPath -Filter "*.csv" | Select-Object Name
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 17 - Script 2
# Merge multiple CSV files into one
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 17"
$ReportsPath = Join-Path $BasePath "Reports"
$CombinedPath = Join-Path $ReportsPath "combined.csv"
$Combined = Get-ChildItem $ReportsPath -Filter "*.csv" |
Where-Object { $_.Name -ne "combined.csv" } |
ForEach-Object {
$SourceFile = $_.Name
Import-Csv $_.FullName | Select-Object *, @{Name="Source_File"; Expression={ $SourceFile }}
}
$Combined | Export-Csv $CombinedPath -NoTypeInformation
Write-Host "Combined CSV created:"
Write-Host $CombinedPath
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 17 - Script 3
# Verify combined CSV
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 17"
$CombinedPath = Join-Path $BasePath "Reports\combined.csv"
$Data = Import-Csv $CombinedPath
Write-Host "Combined rows:" $Data.Count
$Data | Group-Object Source_File |
Select-Object Name, Count |
Format-Table -AutoSize
$Data | Format-Table -AutoSize
Explicación simple del script
- Get-ChildItem lista los CSV de la carpeta.
- Import-Csv lee cada archivo.
- Select-Object * conserva las columnas originales.
- Source_File deja trazabilidad del origen.
- Export-Csv crea el consolidado.
Simple script explanation
- Get-ChildItem lists CSV files in the folder.
- Import-Csv reads each file.
- Select-Object * keeps original columns.
- Source_File leaves origin traceability.
- Export-Csv creates the consolidated file.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| finance.csv | 2 rows |
| hr.csv | 2 rows |
| it.csv | 2 rows |
| combined.csv | 6 rows |
Expected example
| Input / Case | Result |
|---|---|
| finance.csv | 2 rows |
| hr.csv | 2 rows |
| it.csv | 2 rows |
| combined.csv | 6 rows |
Conclusión
Este topic enseña una tarea muy común: consolidar archivos similares en un solo dataset listo para análisis.
Conclusion
This topic teaches a very common task: consolidating similar files into one dataset ready for analysis.