⚠️ 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 16
El objetivo es dividir un CSV grande en partes más pequeñas con una cantidad fija de filas por archivo.
Topic 16 Objective
The goal is to split a large CSV into smaller parts with a fixed number of rows per 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 16"
Qué vamos a aprender
- Crear un CSV sintético grande.
- Definir tamaño de lote.
- Usar índices y rangos.
- Exportar múltiples partes.
- Contar filas por archivo.
What you will learn
- Create a large synthetic CSV.
- Define batch size.
- Use indexes and ranges.
- Export multiple parts.
- Count rows per file.
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 16 - Script 1
# Create a large synthetic CSV
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 16"
$DataPath = Join-Path $BasePath "Data"
$OutputPath = Join-Path $BasePath "Output"
New-Item -Path $DataPath, $OutputPath -ItemType Directory -Force | Out-Null
$BigCsvPath = Join-Path $DataPath "big.csv"
$Rows = 1..2500 | ForEach-Object {
[PSCustomObject]@{
Employee_ID = "E{0:D5}" -f $_
FirstName = "First$_"
LastName = "Last$_"
Department = if ($_ % 2 -eq 0) { "Finance" } else { "Operations" }
}
}
$Rows | Export-Csv $BigCsvPath -NoTypeInformation
Write-Host "Large CSV created:"
Write-Host $BigCsvPath
Write-Host "Rows created:" $Rows.Count
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 16 - Script 2
# Split large CSV into smaller files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 16"
$BigCsvPath = Join-Path $BasePath "Data\big.csv"
$OutputPath = Join-Path $BasePath "Output"
$Rows = Import-Csv $BigCsvPath
$BatchSize = 1000
$PartNumber = 1
for ($i = 0; $i -lt $Rows.Count; $i += $BatchSize) {
$Batch = $Rows[$i..([Math]::Min($i + $BatchSize - 1, $Rows.Count - 1))]
$PartPath = Join-Path $OutputPath ("part_{0:D2}.csv" -f $PartNumber)
$Batch | Export-Csv $PartPath -NoTypeInformation
Write-Host "Created:" $PartPath
$PartNumber++
}
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 16 - Script 3
# Verify split files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 16"
$OutputPath = Join-Path $BasePath "Output"
Get-ChildItem $OutputPath -Filter "part_*.csv" |
ForEach-Object {
[PSCustomObject]@{
File_Name = $_.Name
Row_Count = (Import-Csv $_.FullName).Count
Full_Path = $_.FullName
}
} | Format-Table -AutoSize
Explicación simple del script
- $BatchSize define cuántas filas tendrá cada archivo.
- El ciclo for avanza por bloques.
- Math::Min evita pasarse del último registro.
- Cada parte se exporta como CSV separado.
- La verificación cuenta las filas generadas.
Simple script explanation
- $BatchSize defines how many rows each file will have.
- The for loop moves in batches.
- Math::Min avoids going past the last record.
- Each part is exported as a separate CSV.
- Verification counts the generated rows.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| part_01.csv | 1000 rows |
| part_02.csv | 1000 rows |
| part_03.csv | 500 rows |
Expected example
| Input / Case | Result |
|---|---|
| part_01.csv | 1000 rows |
| part_02.csv | 1000 rows |
| part_03.csv | 500 rows |
Conclusión
Este topic enseña a preparar archivos grandes para cargas controladas o límites de sistemas.
Conclusion
This topic teaches how to prepare large files for controlled uploads or system limits.