⚠️ 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 19
El objetivo es crear un script de limpieza repetible y documentar cómo se ejecutaría de forma programada.
Topic 19 Objective
The goal is to create a repeatable cleanup script and document how it would be run on a schedule.
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 19"
Qué vamos a aprender
- Crear un archivo .ps1 de limpieza.
- Registrar ejecución en un log.
- Simular ejecución manual.
- Preparar comando para Task Scheduler.
- Mantener evidencia de cada corrida.
What you will learn
- Create a cleanup .ps1 file.
- Log execution activity.
- Simulate manual execution.
- Prepare a Task Scheduler command.
- Keep evidence of each run.
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 19 - Script 1
# Create data and reusable cleanup script
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 19"
$DataPath = Join-Path $BasePath "Data"
$ScriptsPath = Join-Path $BasePath "Scripts"
$LogsPath = Join-Path $BasePath "Logs"
New-Item -Path $DataPath, $ScriptsPath, $LogsPath -ItemType Directory -Force | Out-Null
"Temporary file" | Set-Content (Join-Path $DataPath "old_upload.tmp")
"Copy file" | Set-Content (Join-Path $DataPath "report_copy.csv")
"Valid file" | Set-Content (Join-Path $DataPath "clean_report.csv")
$CleanupScript = Join-Path $ScriptsPath "CleanData.ps1"
@'
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 19"
$DataPath = Join-Path $BasePath "Data"
$LogPath = Join-Path $BasePath "Logs\cleanup_log.txt"
"Cleanup started: $(Get-Date)" | Out-File $LogPath -Append
Get-ChildItem $DataPath -File -Include *.tmp, *copy* -Recurse |
ForEach-Object {
"Cleanup candidate: $($_.FullName)" | Out-File $LogPath -Append
Remove-Item $_.FullName -WhatIf
}
"Cleanup finished: $(Get-Date)" | Out-File $LogPath -Append
'@ | Set-Content $CleanupScript
Write-Host "Reusable cleanup script created:"
Write-Host $CleanupScript
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 19 - Script 2
# Run the cleanup script manually
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 19"
$CleanupScript = Join-Path $BasePath "Scripts\CleanData.ps1"
powershell.exe -ExecutionPolicy Bypass -File $CleanupScript
Write-Host "Manual test executed."
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 19 - Script 3
# Show Task Scheduler command and verify log
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 19"
$CleanupScript = Join-Path $BasePath "Scripts\CleanData.ps1"
$LogPath = Join-Path $BasePath "Logs\cleanup_log.txt"
Write-Host "Command that can be used in Task Scheduler:"
Write-Host "powershell.exe -ExecutionPolicy Bypass -File `"$CleanupScript`""
Write-Host ""
Write-Host "Cleanup log:"
Get-Content $LogPath
Explicación simple del script
- El script reusable se guarda como CleanData.ps1.
- Out-File -Append registra cada corrida.
- -WhatIf mantiene la práctica segura.
- El comando final puede configurarse en Task Scheduler.
- El log permite verificar que la ejecución ocurrió.
Simple script explanation
- The reusable script is saved as CleanData.ps1.
- Out-File -Append logs each run.
- -WhatIf keeps the practice safe.
- The final command can be configured in Task Scheduler.
- The log verifies that execution occurred.
Ejemplo esperado
| Entrada / Caso | Resultado |
|---|---|
| CleanData.ps1 | Reusable script |
| cleanup_log.txt | Execution evidence |
| Task Scheduler command | Repeatable automation |
Expected example
| Input / Case | Result |
|---|---|
| CleanData.ps1 | Reusable script |
| cleanup_log.txt | Execution evidence |
| Task Scheduler command | Repeatable automation |
Conclusión
Este topic enseña cómo convertir una limpieza manual en un proceso repetible.
Conclusion
This topic teaches how to turn manual cleanup into a repeatable process.