⚠️ 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 13
El objetivo es identificar filas incompletas en un CSV antes de cargar o cruzar información.
Topic 13 Objective
The goal is to identify incomplete rows in a CSV before uploading or matching information.
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 13"
Qué vamos a aprender
- Crear data con campos vacíos.
- Usar [string]::IsNullOrWhiteSpace().
- Validar múltiples campos críticos.
- Generar un reporte de excepciones.
- Separar registros limpios de registros problemáticos.
What you will learn
- Create data with blank fields.
- Use [string]::IsNullOrWhiteSpace().
- Validate multiple critical fields.
- Generate an exception report.
- Separate clean records from problematic records.
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 13 - Script 1
# Create a CSV with incomplete records
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 13"
$DataPath = Join-Path $BasePath "Data"
$ReportsPath = Join-Path $BasePath "Reports"
New-Item -Path $DataPath, $ReportsPath -ItemType Directory -Force | Out-Null
$CsvPath = Join-Path $DataPath "employees_incomplete.csv"
$Data = @(
[PSCustomObject]@{ Employee_ID = "10001"; FirstName = "John"; Department = "Finance"; Email = "john.smith@example.com" },
[PSCustomObject]@{ Employee_ID = ""; FirstName = "Maria"; Department = "HR"; Email = "maria.garcia@example.com" },
[PSCustomObject]@{ Employee_ID = "10003"; FirstName = "Carlos"; Department = ""; Email = "carlos.rivera@example.com" },
[PSCustomObject]@{ Employee_ID = "10004"; FirstName = "Ana"; Department = "Operations"; Email = "" },
[PSCustomObject]@{ Employee_ID = "10005"; FirstName = ""; Department = "IT"; Email = "robert.lee@example.com" }
)
$Data | Export-Csv $CsvPath -NoTypeInformation
Write-Host "Incomplete CSV created:"
Write-Host $CsvPath
Import-Csv $CsvPath | 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 13 - Script 2
# Find blank or incomplete values
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 13"
$CsvPath = Join-Path $BasePath "Data\employees_incomplete.csv"
Import-Csv $CsvPath |
Where-Object {
[string]::IsNullOrWhiteSpace($_.Employee_ID) -or
[string]::IsNullOrWhiteSpace($_.FirstName) -or
[string]::IsNullOrWhiteSpace($_.Department) -or
[string]::IsNullOrWhiteSpace($_.Email)
} | Format-Table -AutoSize
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 13 - Script 3
# Export incomplete records report
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 13"
$CsvPath = Join-Path $BasePath "Data\employees_incomplete.csv"
$ReportPath = Join-Path $BasePath "Reports\Incomplete_Records_Report.csv"
$Report = Import-Csv $CsvPath | ForEach-Object {
$missing = @()
if ([string]::IsNullOrWhiteSpace($_.Employee_ID)) { $missing += "Employee_ID" }
if ([string]::IsNullOrWhiteSpace($_.FirstName)) { $missing += "FirstName" }
if ([string]::IsNullOrWhiteSpace($_.Department)) { $missing += "Department" }
if ([string]::IsNullOrWhiteSpace($_.Email)) { $missing += "Email" }
if ($missing.Count -gt 0) {
[PSCustomObject]@{
Employee_ID = $_.Employee_ID
FirstName = $_.FirstName
Department = $_.Department
Email = $_.Email
Missing_Fields = ($missing -join ", ")
}
}
}
$Report | Export-Csv $ReportPath -NoTypeInformation
Write-Host "Incomplete records report created:"
Write-Host $ReportPath
$Report | Format-Table -AutoSize
Explicación simple del script
- IsNullOrWhiteSpace detecta valores vacíos o solo espacios.
- -or permite revisar varios campos críticos.
- La lista $missing guarda qué columnas fallan.
- El reporte permite corregir antes de cargar data.
- No se modifica el CSV original.
Simple script explanation
- IsNullOrWhiteSpace detects blanks or values with only spaces.
- -or checks multiple critical fields.
- The $missing list stores which columns fail.
- The report supports correction before upload.
- The original CSV is not modified.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| Missing Employee_ID | Needs review |
| Missing Department | Needs review |
| Missing Email | Needs review |
Expected example
| Input / Case | Result |
|---|---|
| Missing Employee_ID | Needs review |
| Missing Department | Needs review |
| Missing Email | Needs review |
Conclusión
Este topic enseña a detectar registros incompletos antes de que generen errores en sistemas, reportes o cruces de datos.
Conclusion
This topic teaches how to detect incomplete records before they create errors in systems, reports, or data matches.