PowerShell Training · Topic 14

Validar formatos de email

Un ejercicio práctico para detectar correos mal escritos antes de una carga o comunicación masiva.

Validate email formats

A hands-on exercise to detect malformed emails before an upload or mass communication.

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

El objetivo es revisar emails en un CSV y separar los válidos de los que necesitan corrección.

01 · Crear emails mixtos
02 · Validar formato
03 · Exportar inválidos
Idea central: Validar antes de enviar reduce rebotes, errores y retrabajo.

Topic 14 Objective

The goal is to review emails in a CSV and separate valid ones from those that need correction.

01 · Create mixed emails
02 · Validate format
03 · Export invalid
Core idea: Validating before sending reduces bounces, errors, and rework.

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

Qué vamos a aprender

  • Crear una lista con emails válidos e inválidos.
  • Usar una expresión regular básica.
  • Detectar emails sin @, sin dominio o con espacios.
  • Exportar reporte de errores.
  • Preparar data antes de comunicación masiva.

What you will learn

  • Create a list with valid and invalid emails.
  • Use a basic regular expression.
  • Detect emails without @, without domain, or with spaces.
  • Export an error report.
  • Prepare data before mass communication.
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 14 - Script 1
# Create a CSV with valid and invalid emails
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 14"
$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_email.csv"

$Data = @(
    [PSCustomObject]@{ Employee_ID = "10001"; Name = "John Smith"; Email = "john.smith@example.com" },
    [PSCustomObject]@{ Employee_ID = "10002"; Name = "Maria Garcia"; Email = "maria.garciaexample.com" },
    [PSCustomObject]@{ Employee_ID = "10003"; Name = "Carlos Rivera"; Email = "carlos.rivera@" },
    [PSCustomObject]@{ Employee_ID = "10004"; Name = "Ana Lopez"; Email = "ana lopez@example.com" },
    [PSCustomObject]@{ Employee_ID = "10005"; Name = "Robert Lee"; Email = "robert.lee@example.org" }
)

$Data | Export-Csv $CsvPath -NoTypeInformation

Write-Host "Email CSV created:"
Write-Host $CsvPath
Import-Csv $CsvPath | Format-Table -AutoSize
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 14 - Script 2
# Validate email formats
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 14"
$CsvPath = Join-Path $BasePath "Data\employees_email.csv"

Import-Csv $CsvPath |
Where-Object { $_.Email -notmatch "^[^@\s]+@[^@\s]+\.[^@\s]+$" } |
Select-Object Employee_ID, Name, Email
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 14 - Script 3
# Export invalid email report
# ======================================================

$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 14"
$CsvPath = Join-Path $BasePath "Data\employees_email.csv"
$ReportPath = Join-Path $BasePath "Reports\Invalid_Email_Report.csv"

$InvalidEmails = Import-Csv $CsvPath |
Where-Object { $_.Email -notmatch "^[^@\s]+@[^@\s]+\.[^@\s]+$" } |
Select-Object Employee_ID, Name, Email, @{Name="Issue"; Expression={ "Invalid email format" }}

$InvalidEmails | Export-Csv $ReportPath -NoTypeInformation

Write-Host "Invalid email report created:"
Write-Host $ReportPath
$InvalidEmails | Format-Table -AutoSize

Explicación simple del script

  • La expresión regular valida una estructura básica de email.
  • -notmatch devuelve los correos que no cumplen.
  • Se detectan espacios, falta de @ y dominios incompletos.
  • El reporte permite corregir antes de enviar.
  • No garantiza que el buzón exista; solo valida formato.

Simple script explanation

  • The regular expression validates a basic email structure.
  • -notmatch returns emails that do not comply.
  • It detects spaces, missing @, and incomplete domains.
  • The report supports correction before sending.
  • It does not guarantee the mailbox exists; it only validates format.

Ejemplo esperado

Entrada / CasoResultado
maria.garciaexample.comInvalid
carlos.rivera@Invalid
ana lopez@example.comInvalid

Expected example

Input / CaseResult
maria.garciaexample.comInvalid
carlos.rivera@Invalid
ana lopez@example.comInvalid

Conclusión

Este topic enseña a detectar correos mal formados antes de una carga o comunicación masiva.

Lección clave: Validar antes de enviar reduce rebotes, errores y retrabajo.

Conclusion

This topic teaches how to detect malformed emails before an upload or mass communication.

Key lesson: Validating before sending reduces bounces, errors, and rework.