⚠️ 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 7
El objetivo es crear un reporte en CSV que documente los archivos procesados. Este reporte sirve como evidencia de auditoría: qué archivo se revisó, cuánto pesa, cuándo fue modificado y cuál fue el resultado del proceso.
Topic 7 Objective
The goal is to create a CSV report that documents processed files. This report works as audit evidence: which file was reviewed, how large it is, when it was modified, and what the process result was.
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 7"
Qué vamos a aprender
- Crear una carpeta de archivos y otra de reportes.
- Capturar propiedades como Name, Length y LastWriteTime.
- Agregar columnas calculadas como tamaño en KB y resultado.
- Exportar evidencia con Export-Csv.
- Revisar el reporte generado con Import-Csv.
What you will learn
- Create a files folder and a reports folder.
- Capture properties like Name, Length, and LastWriteTime.
- Add calculated columns like size in KB and result.
- Export evidence with Export-Csv.
- Review the generated report with Import-Csv.
Script 1 — Crear data sintética para auditoría
Este script crea archivos de práctica con diferentes tamaños y una carpeta de reportes. La idea es simular un lote de archivos que será documentado.
Script 1 — Create synthetic data for audit
This script creates practice files with different sizes and a reports folder. The idea is to simulate a batch of files that will be documented.
# ======================================================
# Topic 7 - Script 1
# Create synthetic files for reporting
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 7"
$PhotosPath = Join-Path $BasePath "Photos"
$ReportPath = Join-Path $BasePath "Reports"
New-Item -Path $PhotosPath, $ReportPath -ItemType Directory -Force | Out-Null
# Create practice files with different content sizes
"Employee photo file A" | Set-Content -Path (Join-Path $PhotosPath "10001.jpg")
"Employee photo file B with extra metadata" | Set-Content -Path (Join-Path $PhotosPath "10002.jpg")
"Employee photo file C" | Set-Content -Path (Join-Path $PhotosPath "10003.jpg")
"Rejected file missing official ID" | Set-Content -Path (Join-Path $PhotosPath "NoMatch_9999.jpg")
"Temporary upload pending review" | Set-Content -Path (Join-Path $PhotosPath "Temp_Upload_8001.jpg")
Write-Host "Synthetic files created in:" $PhotosPath
Get-ChildItem $PhotosPath -File | Select-Object Name, Length, LastWriteTime
Script 2 — Crear reporte de archivos procesados
Este script lee los archivos de la carpeta, selecciona propiedades importantes y agrega columnas calculadas para documentar el proceso.
Script 2 — Create processed files report
This script reads the files from the folder, selects important properties, and adds calculated columns to document the process.
# ======================================================
# Topic 7 - Script 2
# Create processed files report
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 7"
$PhotosPath = Join-Path $BasePath "Photos"
$ReportsPath = Join-Path $BasePath "Reports"
$CsvPath = Join-Path $ReportsPath "Photo_Report.csv"
Get-ChildItem $PhotosPath -File |
Select-Object `
Name,
FullName,
Extension,
Length,
@{Name="Size_KB"; Expression={ [math]::Round($_.Length / 1KB, 2) }},
LastWriteTime,
@{Name="Process_Result"; Expression={
if ($_.BaseName -match "^\d+$") { "Valid ID format" }
else { "Needs manual review" }
}} |
Export-Csv $CsvPath -NoTypeInformation
Write-Host "Report created:"
Write-Host $CsvPath
Script 3 — Verificar el reporte generado
Este script importa el CSV y muestra el reporte en pantalla para confirmar que se generó correctamente.
Script 3 — Verify the generated report
This script imports the CSV and displays the report on screen to confirm it was generated correctly.
# ======================================================
# Topic 7 - Script 3
# Verify generated CSV report
# ======================================================
$BasePath = "$env:USERPROFILE\Documents\AI Practical Training\PowerShell\Topic 7"
$CsvPath = Join-Path $BasePath "Reports\Photo_Report.csv"
Import-Csv $CsvPath |
Select-Object Name, Size_KB, LastWriteTime, Process_Result |
Format-Table -AutoSize
Write-Host ""
Write-Host "CSV report location:"
Write-Host $CsvPath
Explicación simple del script
- Get-ChildItem -File obtiene los archivos procesados.
- Select-Object elige las columnas del reporte.
- Length guarda el tamaño en bytes.
- Size_KB convierte el tamaño a kilobytes.
- Process_Result agrega una evaluación simple del archivo.
- Export-Csv crea el reporte final.
Simple script explanation
- Get-ChildItem -File gets the processed files.
- Select-Object chooses the report columns.
- Length stores size in bytes.
- Size_KB converts size to kilobytes.
- Process_Result adds a simple file evaluation.
- Export-Csv creates the final report.
Ejemplo esperado
| Archivo | Resultado |
|---|---|
| 10001.jpg | Valid ID format |
| 10002.jpg | Valid ID format |
| NoMatch_9999.jpg | Needs manual review |
| Temp_Upload_8001.jpg | Needs manual review |
Expected example
| File | Result |
|---|---|
| 10001.jpg | Valid ID format |
| 10002.jpg | Valid ID format |
| NoMatch_9999.jpg | Needs manual review |
| Temp_Upload_8001.jpg | Needs manual review |
Conclusión
Este topic enseña una práctica clave: todo proceso automatizado debe dejar evidencia. Un reporte simple con nombre, ruta, tamaño, fecha y resultado ayuda a revisar lo ejecutado, detectar excepciones y documentar el trabajo.
Conclusion
This topic teaches a key practice: every automated process should leave evidence. A simple report with name, path, size, date, and result helps review what was executed, detect exceptions, and document the work.