⚠️ 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 10
El objetivo es limpiar una carpeta eliminando archivos temporales o basura, pero siguiendo un flujo responsable: primero listar, luego simular, después reportar y finalmente eliminar solo lo que cumple reglas claras.
Topic 10 Objective
The goal is to clean a folder by removing temporary or junk files, but using a responsible workflow: first list, then simulate, then report, and finally remove only what matches clear rules.
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 10"
Qué vamos a aprender
- Crear archivos válidos y archivos basura.
- Usar -Include con patrones como *.tmp y *copy*.
- Usar -Recurse para revisar subcarpetas.
- Simular eliminación con Remove-Item -WhatIf.
- Crear un reporte antes de borrar.
What you will learn
- Create valid files and junk files.
- Use -Include with patterns like *.tmp and *copy*.
- Use -Recurse to scan subfolders.
- Simulate deletion with Remove-Item -WhatIf.
- Create a report before deleting.
Script 1 — Crear data sintética con archivos temporales
Este script crea archivos válidos y archivos que simulan basura: temporales, copias antiguas, backups accidentales y archivos en subcarpetas.
Script 1 — Create synthetic data with temporary files
This script creates valid files and files that simulate junk: temporary files, old copies, accidental backups, and files in subfolders.
# ======================================================
# Topic 10 - Script 1
# Create synthetic temporary and junk files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 10"
$DataPath = Join-Path $BasePath "Data"
$SubPath = Join-Path $DataPath "Subfolder"
$ReportsPath = Join-Path $BasePath "Reports"
New-Item -Path $DataPath, $SubPath, $ReportsPath -ItemType Directory -Force | Out-Null
# Valid files
"Valid employee photo" | Set-Content -Path (Join-Path $DataPath "10001.jpg")
"Valid employee photo" | Set-Content -Path (Join-Path $DataPath "10002.jpg")
"Valid report" | Set-Content -Path (Join-Path $DataPath "Final_Report.csv")
# Junk / temporary files
"Temporary file" | Set-Content -Path (Join-Path $DataPath "upload.tmp")
"Old copy" | Set-Content -Path (Join-Path $DataPath "10001_copy.jpg")
"Old copy" | Set-Content -Path (Join-Path $DataPath "Final_Report_copy.csv")
"Backup by mistake" | Set-Content -Path (Join-Path $DataPath "notes.bak")
"Rejected temp" | Set-Content -Path (Join-Path $SubPath "old_export.tmp")
"Another copy" | Set-Content -Path (Join-Path $SubPath "photo_copy_old.jpg")
Write-Host "Synthetic data created in:" $DataPath
Get-ChildItem $DataPath -Recurse -File | Select-Object Name, Extension, DirectoryName
Script 2 — Identificar archivos candidatos a limpieza
Este script identifica los archivos que cumplen reglas de limpieza. Todavía no borra nada; solo muestra los candidatos y crea un reporte.
Script 2 — Identify cleanup candidates
This script identifies files that match cleanup rules. It does not delete anything yet; it only displays the candidates and creates a report.
# ======================================================
# Topic 10 - Script 2
# Identify temporary or junk files and create report
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 10"
$DataPath = Join-Path $BasePath "Data"
$ReportPath = Join-Path $BasePath "Reports\Cleanup_Candidates_Report.csv"
$Candidates = Get-ChildItem $DataPath -File -Recurse -Include *.tmp, *copy*, *.bak |
Select-Object `
Name,
FullName,
Extension,
Length,
LastWriteTime,
@{Name="Cleanup_Reason"; Expression={
if ($_.Extension -eq ".tmp") { "Temporary file" }
elseif ($_.Name -like "*copy*") { "Copy file" }
elseif ($_.Extension -eq ".bak") { "Backup file" }
else { "Cleanup candidate" }
}}
$Candidates | Export-Csv -Path $ReportPath -NoTypeInformation
Write-Host "Cleanup candidates found:"
$Candidates | Format-Table Name, Extension, Cleanup_Reason -AutoSize
Write-Host ""
Write-Host "Report created:"
Write-Host $ReportPath
Script 3 — Simular y eliminar con control
Primero se ejecuta una simulación con -WhatIf. Solo después de verificar el resultado, se puede correr la sección real de eliminación.
Script 3 — Simulate and remove with control
First, run a simulation with -WhatIf. Only after verifying the result should the real deletion section be run.
# ======================================================
# Topic 10 - Script 3
# Simulate and remove temporary or junk files
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 10"
$DataPath = Join-Path $BasePath "Data"
# Step A - Simulation only
Get-ChildItem $DataPath -File -Recurse -Include *.tmp, *copy*, *.bak |
Remove-Item -WhatIf
# Step B - Real deletion
# IMPORTANT:
# Run this section only after reviewing the report and the WhatIf output.
# Remove the comment symbol # from the next two lines only when approved.
# Get-ChildItem $DataPath -File -Recurse -Include *.tmp, *copy*, *.bak |
# Remove-Item
Explicación simple del script
- Get-ChildItem busca archivos dentro de la carpeta.
- -Recurse incluye subcarpetas.
- -Include *.tmp, *copy*, *.bak define los patrones de limpieza.
- Export-Csv deja evidencia antes de borrar.
- Remove-Item -WhatIf muestra qué se eliminaría sin borrar nada.
Simple script explanation
- Get-ChildItem searches files inside the folder.
- -Recurse includes subfolders.
- -Include *.tmp, *copy*, *.bak defines the cleanup patterns.
- Export-Csv leaves evidence before deletion.
- Remove-Item -WhatIf shows what would be deleted without removing anything.
Ejemplo esperado
| Archivo | Razón |
|---|---|
| upload.tmp | Temporary file |
| 10001_copy.jpg | Copy file |
| Final_Report_copy.csv | Copy file |
| notes.bak | Backup file |
Expected example
| File | Reason |
|---|---|
| upload.tmp | Temporary file |
| 10001_copy.jpg | Copy file |
| Final_Report_copy.csv | Copy file |
| notes.bak | Backup file |
Conclusión
Este topic enseña una de las tareas más delicadas de automatización: eliminar archivos. La clave no es borrar rápido; la clave es identificar bien, reportar, simular y eliminar solamente cuando las reglas están claras.
Conclusion
This topic teaches one of the most sensitive automation tasks: deleting files. The key is not deleting fast; the key is identifying correctly, reporting, simulating, and deleting only when the rules are clear.