⚠️ 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 18
El objetivo es capturar errores durante un proceso y guardarlos en un log para revisión.
Topic 18 Objective
The goal is to capture errors during a process and save them in a log for review.
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 18"
Qué vamos a aprender
- Crear un proceso con casos exitosos y fallidos.
- Usar try y catch.
- Guardar errores con fecha y archivo.
- Continuar el proceso aunque algo falle.
- Revisar el log final.
What you will learn
- Create a process with successful and failed cases.
- Use try and catch.
- Save errors with date and file.
- Continue processing even when something fails.
- Review the final log.
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 18 - Script 1
# Create files and lookup data with an intentional error
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 18"
$DataPath = Join-Path $BasePath "Data"
$LogsPath = Join-Path $BasePath "Logs"
New-Item -Path $DataPath, $LogsPath -ItemType Directory -Force | Out-Null
"Valid file" | Set-Content (Join-Path $DataPath "10001.txt")
"Valid file" | Set-Content (Join-Path $DataPath "10002.txt")
"No match file" | Set-Content (Join-Path $DataPath "99999.txt")
$LookupPath = Join-Path $DataPath "lookup.csv"
@(
[PSCustomObject]@{ Old_ID = "10001"; New_ID = "E10001" },
[PSCustomObject]@{ Old_ID = "10002"; New_ID = "E10002" }
) | Export-Csv $LookupPath -NoTypeInformation
Write-Host "Training files and lookup created:"
Get-ChildItem $DataPath | 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 18 - Script 2
# Process files and create error log
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 18"
$DataPath = Join-Path $BasePath "Data"
$LookupPath = Join-Path $DataPath "lookup.csv"
$LogPath = Join-Path $BasePath "Logs\errors.txt"
$Lookup = Import-Csv $LookupPath
Get-ChildItem $DataPath -Filter "*.txt" | ForEach-Object {
try {
$id = $_.BaseName
$match = $Lookup | Where-Object { $_.Old_ID -eq $id }
if (-not $match) {
throw "No lookup match found for ID $id"
}
$newName = "$($match.New_ID)$($_.Extension)"
Rename-Item -Path $_.FullName -NewName $newName -ErrorAction Stop
Write-Host "Renamed:" $_.Name "to" $newName
}
catch {
$message = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') | File: $($_.Name) | Error: $($_.Exception.Message)"
$message | Out-File $LogPath -Append
Write-Host "Logged error for:" $_.Name -ForegroundColor Yellow
}
}
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 18 - Script 3
# Review error log and final files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 18"
$DataPath = Join-Path $BasePath "Data"
$LogPath = Join-Path $BasePath "Logs\errors.txt"
Write-Host "Final files:"
Get-ChildItem $DataPath | Select-Object Name
Write-Host ""
Write-Host "Error log:"
if (Test-Path $LogPath) {
Get-Content $LogPath
} else {
Write-Host "No errors logged."
}
Explicación simple del script
- try intenta ejecutar la acción principal.
- throw crea un error controlado cuando no hay match.
- catch captura el error sin detener todo el proceso.
- Out-File -Append agrega el error al log.
- El log deja evidencia del fallo.
Simple script explanation
- try attempts the main action.
- throw creates a controlled error when there is no match.
- catch captures the error without stopping the full process.
- Out-File -Append adds the error to the log.
- The log leaves evidence of the failure.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| 10001.txt | Renamed |
| 10002.txt | Renamed |
| 99999.txt | Logged error |
Expected example
| Input / Case | Result |
|---|---|
| 10001.txt | Renamed |
| 10002.txt | Renamed |
| 99999.txt | Logged error |
Conclusión
Este topic enseña transparencia operativa: cuando algo falla, el proceso no debe quedar en silencio.
Conclusion
This topic teaches operational transparency: when something fails, the process should not stay silent.